繁体   English   中英

尝试使用连接器表连接 Sequelize 中的两个数据库表

[英]Trying to connect two database tables in Sequelize with a joiner table

我正在尝试查询与用户关联的所有商家。

共有三张表:

user_tbluser_favorite_tblmerchant_tbl

对于每个,我都创建了一个 Sequelize 实例。

用户、用户收藏夹和商家。

我正在尝试进行一个查询,该查询将让我每个用户都通过 user_favorite_tbl 收藏每个商家。

这是我的代码:

public async fetch_user_with_favorite() {
    let favMerchants = await User.findAll({
        attributes: ["given_name", "family_name", "email"],
        include: [
            {
                model: UserFavorite,
                attributes: ["merchant_id"],
                include: [
                    {
                        model: Merchant,
                        attributes: ["name"]
                    }
                ]
            }
        ]
    });
    return favMerchants;
}

User.belongsToMany(Merchant, { through: "user_favorite_tbl" });
Merchant.belongsToMany(User, { through: "user_favorite_tbl" });

但是,当我尝试调用与此代码关联的端点时,出现以下错误:

SequelizeEagerLoadingError: user_favorite_tbl is not associated to user_tbl!

当我尝试添加此内容时:

User.hasMany(UserFavorite, { foreignKey: "user_id" });
Merchant.hasMany(UserFavorite, { foreignKey: "merchant_id" });

我收到此错误:

SequelizeEagerLoadingError: merchant_tbl is not associated to user_favorite_tbl!

我到底哪里错了?

您可以定义如下关联-可以使用如下两个一对多关系来实现多对多关系-

User.hasMany(UserFavorite, { foreignKey: 'user_id', targetKey: 'id'});
UserFavorite.hasMany(User,{ foreignKey: 'user_id',targetKey: 'id'});
Merchant.hasMany(UserFavorite, { foreignKey: 'merchant_id', targetKey: 'id'});
UserFavorite.hasMany(Merchant,{ foreignKey: 'merchant_id',targetKey: 'id'});

您的belongsToMany关联看起来是正确的,但是,当您有belongsToMany ,您的findAll不应该在includeinclude中间表。 through在内部处理中间表关联。

let favMerchants = await User.findAll({
    attributes: ["given_name", "family_name", "email"],
    include: [
        {
            model: Merchant,
            attributes: ["name"],
            through: { attributes: [] } // if you do not need any metadata in user_favorite_tbl.
        }
    ]
});

附注

User.belongsToMany(Merchant, { through: "user_favorite_tbl" });

这可能更好用

User.belongsToMany(Merchant, { through: UserFavorite });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM