[英]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.