gpt4 book ai didi

javascript - 如何在 sequelize.js 中有条件地加载关联?

转载 作者:行者123 更新时间:2023-12-03 22:41:56 24 4
gpt4 key购买 nike

Post.findAndCountAll({
include: [{
model: models.like,
where: { userId: req.authSession.user.id }
]}
}).then( collection => {
onSucess(collection);
});

如果帖子具有来自用户的关联赞,这将加载帖子。但是,我想要的是加载所有用户的帖子并加载相关联的帖子(如果存在)。我可以用 sequelize.js 以某种方式存档这种行为吗?

最佳答案

您只需要在上一层嵌套 where 子句。

Post.findAndCountAll({
where: { userId: req.authSession.user.id },
include: [{model: models.like}]
}).then( collection => {
onSucess(collection);
});

这将返回所有具有 userId === req.authSession.user.id 的帖子,并将包括他们的喜欢(如果有)。

根据评论编辑

如果您想获得用户的赞,您可以还原查询
Like.findAndCountAll({ 
where: { userId: req.authSession.user.id },
include: [ { model: models.post } ]
});

关于javascript - 如何在 sequelize.js 中有条件地加载关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com