簡體   English   中英

Sequelize - 一對多關系延遲加載並返回一個實例而不是一個集合

[英]Sequelize - One to Many relationship lazy load and return one instance and not a collection

尋找一種延遲加載 hasMany 關系但只返回關系的一個實例而不是集合的方法。

期望輸出

{
  id: 5,
  note: 'Hello World',
  date: '2019-10-12',
}

我得到的輸出

[
  {
    id: 5,
    note: 'Hello World',
    date: '2019-10-12',
  }
]

我目前擁有的代碼是

....
const note = await user.getNotes({
  limit: 1,
  where: {
    date: moment('2019-10-12')
  }
});

有沒有一種方法可以在延遲加載時只獲取該筆記的一個實例,而不是在加載該關系后必須使用note[0]

最簡單的方法是解構數組並將note的值設置為第一個元素:

const [ note ] = await user.getNotes({
  limit: 1,
  where: {
    date: moment('2019-10-12')
  }
});

您還可以使用Note.findOne()並將user.id傳遞給where子句。 在內部,這有效地執行與上述相同的事情。

const note = await Note.findOne({
  limit: 1,
  where: {
    user_id: user.id,
    date: moment('2019-10-12')
  }
});

暫無
暫無

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

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