【问题标题】:Sequelize the nodejs throught model association通过模型关联对nodejs进行续集
【发布时间】:2015-09-19 19:42:40
【问题描述】:

我有树模型UserCompanyUserCompany。 我有联想

        Company.belongsToMany(User, {
            as: 'users',
            through: {
                model: UserCompany,
                unique: false
            },
            onDelete: 'cascade'
        });

        User.belongsToMany(Company, {
            as: 'companies',
            through: {
                model: UserCompany,
                unique: false
            },
            onDelete: 'cascade'
        });

我正在尝试查询购买运行此代码的公司

sql.Company.findAll({
    where: query,
    include: [{model:sql.User, as:'users', attributes: ['id', 'first_name', 'last_name', 'email']}],
    order: sort,
    limit: limit,
    offset: offset
})

我有UserCompanyCompanyId=10UserId=50 的两个元素,但查询只返回其中一个。 它返回数组

{id: 10,
 ...,
 users: {
     id: 50,
     ...,
     UserCompany: {}
 }
}

所以UserCompany 不是数组,它只是一个元素。但我想把它们全部拿走。 如何修复我的关联代码?

【问题讨论】:

    标签: sql node.js associations sequelize.js


    【解决方案1】:

    你的联想是对的。 UserCompany 属性不应该显示每个用户的所有 UserCompany 关系 - 它只是显示使用户包含在该查询结果中的关系。

    如果您要查找的是与返回数组中的每个用户关联的公司列表,您可以为此添加 include

    Company.findAll({
        include: [{  
            model: User, 
            as: 'users', 
            attributes: ['id', 'first_name', 'last_name', 'email'], 
    
            // Add this
            include: [{  
                model: Company, 
                as: 'companies', 
                attributes: ['id', 'name'] 
            }], 
        }],
    })
    

    这会在返回的数组中为您提供以下格式:

    {
      id: 1,
      first_name: 'Nelson',
      last_name: 'Bighetti',
      email: 'bighead@hooli.com',
      UserCompany: {...},
      companies: [
        { id: 1, name: 'Hooli', UserCompany: {...} },
        { id: 2, name: 'Pied Piper', UserCompany: {...} }
      ]
    }
    

    【讨论】:

    • 非常感谢您的帮助,但恐怕我的问题还不清楚。现在我编辑了它。如果可能的话,请您帮我解决这个问题。
    • 仍然不确定我是否理解。您有两个重复的 UserCompany 条目链接同一公司和用户?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2021-03-20
    • 2018-02-28
    • 2018-06-27
    相关资源
    最近更新 更多