You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sequelize的一个Scope中调用另一模型的Scope?

解决方案

Sequelize 本身支持在 include 关联查询时直接调用关联模型的 scope,有两种常用实现方式,最终效果和你写的嵌套 include 完全一致:

方式1:使用官方提供的 scope 嵌套语法(推荐)

如果 includeStudentAndTutor 是定义在 BookingSession 模型上的 scope,直接在关联配置中指定要调用的 scope 即可:

includeBookingSessionAndUsers: (userId) => ({
    include: [
        {
            model: sequelize.model('BookingSession'),
            where: {
                [Op.or]: [
                    { studentId: userId },
                    { tutorId: userId },
                ],
            },
            // 调用关联模型的指定scope
            scope: 'includeStudentAndTutor'
        },
    ],
}),

如果要调用的 scope 带参数,写法为 scope: ['scope名称', 参数1, 参数2]。

方式2:手动解构 scope 返回的配置

如果不想用 scope 嵌套语法,也可以直接取出对应 scope 返回的 include 配置嵌入:

includeBookingSessionAndUsers: (userId) => ({
    include: [
        {
            model: sequelize.model('BookingSession'),
            where: {
                [Op.or]: [
                    { studentId: userId },
                    { tutorId: userId },
                ],
            },
            // 直接获取BookingSession对应scope返回的include配置
            include: sequelize.model('BookingSession').scope('includeStudentAndTutor').include
        },
    ],
}),

内容的提问来源于stack exchange,提问作者Gelloiss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:06:05