你好,我需要你的帮助,请回答两个问题。
我有两个模特儿一对多
(One) Customer{ id, names, dni} -> Invoice {id, date, ....customer_id} (Many)如何获得1 ?我需要使用api "GET /api/“,然后json返回一个数组。
[{
id: 1,
date: '2022-01-01',
....invoice
customer: {
dni: 1,
names: 'Example'
}
},
{
id: 2,
date: '2022-01-02',
....invoice
customer: {
dni: 2,
names: 'Example 2'
}
},
]到目前为止,我在sailsjs文档中发现的只是填充的示例,其中只展示了如何列出用户模型及其相应的创建模型(hasMany)。
//var users = await User.find().populate('pets');
// The users object would look something like the following
// [{
// id: 123,
// firstName: 'Foo',
// lastName: 'Bar',
// pets: [{
// id: 1,
// breed: 'labrador',
// type: 'dog',
// name: 'fido',
// user: 123
// }]
// }]
//---This is not what I need.是否有未找到的函数或配置?还是我会做这样的事?
Invoices.find().exec(async(err, invoices)=>{
if(invoices){
for(i = 0; i< invoices.length; i++){
const customer = await Customer.find({id: invoices[i].customer_id});
invoices[i].customer = customer;
}
});关键是,这比使用联接执行查询花费的时间长得多。
const invoices = await sails.sendNativeQuery('SELECT * from INVOICE A A inner join CUSTOMER B on A.customer_id=B.id ', []);但是,如果我通过查询来实现JSON,我就不知道如何用前面的结构来获得JSON。
2.解决我的问题的最佳选择是什么?
发布于 2022-05-22 02:37:18
populate方法在两个方向工作:oneToMany、manyToMany和manyToOne
https://sailsjs.com/documentation/reference/waterline-orm/queries/populate
如果需要任何条件,可以检查Populating a collection association部分的详细信息。
var usersNamedFinn = await User.find({ name:'Finn' })
.populate('currentSwords', {
where: {
color: 'purple'
},
limit: 3,
sort: 'hipness DESC'
});https://stackoverflow.com/questions/72277034
复制相似问题