首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BelongsTo in Sails.js

BelongsTo in Sails.js
EN

Stack Overflow用户
提问于 2022-05-17 15:44:19
回答 1查看 19关注 0票数 0

你好,我需要你的帮助,请回答两个问题。

我有两个模特儿一对多

代码语言:javascript
复制
(One) Customer{ id, names, dni} -> Invoice {id, date, ....customer_id} (Many)

如何获得1 ?我需要使用api "GET /api/“,然后json返回一个数组。

代码语言:javascript
复制
[{
 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)。

代码语言:javascript
复制
//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.

是否有未找到的函数或配置?还是我会做这样的事?

代码语言:javascript
复制
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;
            }
});

关键是,这比使用联接执行查询花费的时间长得多。

代码语言:javascript
复制
   const invoices = await sails.sendNativeQuery('SELECT * from INVOICE A A inner join CUSTOMER B on A.customer_id=B.id ', []);

但是,如果我通过查询来实现JSON,我就不知道如何用前面的结构来获得JSON。

2.解决我的问题的最佳选择是什么?

EN

回答 1

Stack Overflow用户

发布于 2022-05-22 02:37:18

populate方法在两个方向工作:oneToManymanyToManymanyToOne

https://sailsjs.com/documentation/reference/waterline-orm/queries/populate

如果需要任何条件,可以检查Populating a collection association部分的详细信息。

代码语言:javascript
复制
var usersNamedFinn = await User.find({ name:'Finn' })
.populate('currentSwords', {
  where: {
    color: 'purple'
  },
  limit: 3,
  sort: 'hipness DESC'
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72277034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档