簡體   English   中英

Sails.js 中的 BelongsTo

[英]BelongsTo in Sails.js

您好,我需要您的幫助,請問兩個問題。

我有 2 個模型一對多

(One) Customer{ id, names, dni} -> Invoice {id, date, ....customer_id} (Many)

1.我怎樣才能得到這個? 我需要使用 api "GET /api/invoices" 並且 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 文檔中發現的只是 POPULATE 的示例,其中它們僅顯示如何列出用戶 model 及其相應創建的用戶 (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.

是不是有function或者我沒有找到的配置? 或者我會做這樣的事情嗎?

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;
            }
});

關鍵是這比使用 join 進行查詢要花費更長的時間

   const invoices = await sails.sendNativeQuery('SELECT * from INVOICE A A inner join CUSTOMER B on A.customer_id=B.id ', []);

但是我不知道如何通過查詢獲得具有先前結構的 JSON

2. 什么是可以解決我的問題的最佳選擇?

populate方法雙向工作: oneToManymanyToManymanyToOne

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'
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM