[英]Sequelize.js,How to insert a model with one to many to many relationship
[英]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.