【问题标题】:Sequelize help in associations续集帮助协会
【发布时间】:2016-11-01 18:55:09
【问题描述】:

所有,下面附上一个 SQL 查询,我在 sequelize 中用作原始查询,它运行良好。现在我正在尝试在 sequelize 中使用 mixin 关联来设置它,但无法这样做。确实浏览了帮助文档,但无法完全掌握细节。也许它只是我。无论如何,下面附上我正在尝试修改的查询。如果有人可以提出一些指示或有一些样本来帮助我重做这个,我将不胜感激?提前致谢。

select cust.*, cust_role.id, cust_role.rolename, role.roletype
from
customer cust, customer_roles cust_role, roles role
where
cust.id = cust_role.user and
cust_role.role = role.id and
cust.id like '0123456' //customerId

表关系

customer_roles has a foreign key to both roles and customer tables
customer to customer_roles (1 to many), 
customer_roles to roles (many to 1)

我正在导入模型

var custModel = sequelize.import('../models/customer.js');
var custRolesModel = sequelize.import('../models/customer_roles.js');
var roleModel = sequelize.import('../models/roles.js');

试图建立关系

custModel.hasMany(custRolesModel);
custRolesModel.belongsTo(custModel);

roleModel.hasMany(custRolesModel);
custRolesModel.belongsTo(roleModel);

最后试图吸引客户..

custModel.findAll({
  include:[{
    model:custRolesModel,
    include:[{
      model:roleModel,
      where: {
        username:req.body.username
      },
      required:false
    }]
  }]
}).then(function (result) {
......

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    根据上面的建议和 SO 中的另一个建议,我能够解决它。这就是我所做的,以防有人需要知道。

    https://stackoverflow.com/a/36006808/1657861

    修改后的关系

    custModel.belongsToMany(custRolesModel, {
      through:'customer_roles', //Used table name
      foreignKey: 'user',
      otherKey:'id'
    });
    
    custRolesModel.belongsToMany(roleModel, {
      through: 'customer_roles', //Used table name
      foreignKey: 'role',
      otherKey: 'id'
    });
    
    usersModel.findAll({
      where : {
        username:req.body.username
      },
      include:[{
        model:userRolesMembershipModel,
        include:[{
          model:roleModel
        }]
      }]
    })
    

    【讨论】:

      【解决方案2】:

      这可能有效:

      custModel.findAll({
        where : {
          id:req.body.userId
        },
        include:[{
          model:custRolesModel,
          include:[{
            model:roleModel
          }]
        }]
      }).then(function (result) {
      ......
      

      注意 where 子句属于客户模型而不是角色模型。

      【讨论】:

      • 感谢您的回复。尝试了您的建议,生成的 SQL 关联不正确。例如 cust.id = cust_role.UserId ,其中 UserId 列不存在于 cust_role 表中。很少有像这样的错误联想。关于为什么会发生这种情况以及我应该寻找什么的任何想法?
      • 你有没有试过在模型更改后删除数据库? Sequelize 不会更改列。如果您删除数据库并使用 Sequelize.sync(),则应该存在 UserId 列,假设您的关联设置正确。顺便说一句,UserId 来自哪个模型?
      • 将尝试删除数据库。用户 ID 在 custModel 中。
      • 最后,我得到了这个工作。您的建议与 SO 中的另一个建议相结合,能够解决此问题。我没有删除数据库。把它作为最后的手段。但无论如何,非常感谢你的帮助。我已经添加了我的解决方案。
      • 太棒了。感谢您分享您的解决方案!
      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      相关资源
      最近更新 更多