gpt4 book ai didi

many-to-many - Sequelize Query - 根据多对多表和父表查找记录

转载 作者:行者123 更新时间:2023-12-03 22:20:29 25 4
gpt4 key购买 nike

给定以下 Sequelize 模型:

var User = db.define('user', {
name: Sequelize.STRING
});


var Group = db.define('group', {
name: Sequelize.STRING,
public : { type: Sequelize.BOOLEAN, defaultValue: true }
});

Group.belongsToMany(User, { as: 'specialUsers', through: 'user_groups', foreignKey: 'group_id' });


User.belongsToMany(Group, { through: 'user_groups', foreignKey: 'user_id' });

我将如何通过 Groups 模型查找 Groups,其中返回的 Groups 应该是用户在多对多表中具有记录的那些 - 或者 - 该组是公共(public)组?

我试过这样的事情:
return Group.findAll({
attributes: ['name', 'public'],
include: [{
model: User,
as: 'specialUsers',
where: {
$or : [
{name: 'Neill'},
Sequelize.literal('"group"."public" = true')
]
}
}]
});

最佳答案

return Group.findAll({
attributes: ['name', 'public'],
include: [{
model: User,
as: 'specialUsers',
}],
where: {
$or : {
'$users.name$": 'Neill',
public: true
}
}
});

如果您使用的是相当新的版本,则应该可以使用。请注意,我将 where 移出包含

关于many-to-many - Sequelize Query - 根据多对多表和父表查找记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35210803/

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