首页 > 解决方案 > Sequelize,我如何从多个表中找到

问题描述

我正在使用 Sequelize 从多个表中进行选择,目前正在寻找一种在 E.tmpField 上包含约束的方法,下面的示例不起作用...

await A.findOne({

                include: [
                    {
                        model: B,
                        include: [
                            {
                                model: C,
                                include: [D, E],
                            },
                        ],
                    },
                    {
                        model: F,
                        include: [G],
                    },
                ],
                where: {
                    name: { [Op.in]: nameList },
                    $and: [{ '$E.tmpField$': 100 }],
                },
            });

标签: ormsequelize.jssequelize-typescript

解决方案


您可以为每个预先加载的模型指定 where 选项:

await A.findOne({
    where: {
        name: { [Op.in]: nameList } // Where option for model A
    },
    include: [
        {
            model: B,
            include: [
                {
                    model: C,
                    include: [
                        {
                            model: D
                        },
                        {
                            model: E,
                            where: {
                                tmpField: 100 // Where option for model E
                            }
                        }
                    ],
                },
            ],
        },
        {
            model: F,
            include: [G],
        },
    ]
});

推荐阅读