Sequelize 多对多查询模型
Sequelize Many-to-many querying model
查询数据有一些问题。
有 2 个具有多对多关系的模型。
第一个 - S3FileData,第二个 - 播放列表,它们通过 PlaylistContent table 连接。
S3FileData 也与用户连接,用户拥有许多播放列表。
我需要查询属于用户但不在用户播放列表中的S3文件。
我有播放列表 ID,用户 ID。
我还需要 offset 和 limit 方法,所以我尝试使用 findAndCountAll
进行查询
但是运气不好。
非常感谢任何帮助:)
您将需要 include(joins in SQL) 来连接所有这些表。
像这样,但首先你需要交织你的模型(数据库表),它看起来像这样:
User.belongsToMany(Profile, { through: Grant });
Profile.belongsToMany(User, { through: Grant });
User.hasMany(Grant);
Grant.belongsTo(User);
Profile.hasMany(Grant);
Grant.belongsTo(Profile);
Reference:
https://sequelize.org/master/manual/advanced-many-to-many.html
现在,完成连接后,您将需要在 findAll
(或根据要求 findAllAndCount
)中使用 include 关键字来使用这些连接:
一些基本代码(您需要相应地尝试和调整,这是粗略的代码):
S3Files.findAll({
include: [
{
model: user,
attributes: ['some columns']
include: {
model: userPlaylist,
attributes: ['some columns'],
required: false
},
where: {[Op.and]: Sequelize.where(Sequelize.col('userPlaylist.userId'), 'is not' null)},
attributes: ['some columns']
]
});
最后,对于偏移量和限制,您需要 LIMIT
和 OFFSET
的基本 SQL 逻辑
偏移量和限制的官方文档示例片段:
Project
.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
})
Reference for the same:
https://sequelize.org/v5/manual/models-usage.html
查询数据有一些问题。 有 2 个具有多对多关系的模型。 第一个 - S3FileData,第二个 - 播放列表,它们通过 PlaylistContent table 连接。 S3FileData 也与用户连接,用户拥有许多播放列表。
我需要查询属于用户但不在用户播放列表中的S3文件。
我有播放列表 ID,用户 ID。
我还需要 offset 和 limit 方法,所以我尝试使用 findAndCountAll
进行查询但是运气不好。 非常感谢任何帮助:)
您将需要 include(joins in SQL) 来连接所有这些表。 像这样,但首先你需要交织你的模型(数据库表),它看起来像这样:
User.belongsToMany(Profile, { through: Grant });
Profile.belongsToMany(User, { through: Grant });
User.hasMany(Grant);
Grant.belongsTo(User);
Profile.hasMany(Grant);
Grant.belongsTo(Profile);
Reference: https://sequelize.org/master/manual/advanced-many-to-many.html
现在,完成连接后,您将需要在 findAll
(或根据要求 findAllAndCount
)中使用 include 关键字来使用这些连接:
一些基本代码(您需要相应地尝试和调整,这是粗略的代码):
S3Files.findAll({
include: [
{
model: user,
attributes: ['some columns']
include: {
model: userPlaylist,
attributes: ['some columns'],
required: false
},
where: {[Op.and]: Sequelize.where(Sequelize.col('userPlaylist.userId'), 'is not' null)},
attributes: ['some columns']
]
});
最后,对于偏移量和限制,您需要 LIMIT
和 OFFSET
偏移量和限制的官方文档示例片段:
Project
.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
})
Reference for the same: https://sequelize.org/v5/manual/models-usage.html