【问题标题】:Eager loading an associated entity on the model definition with sequelizejs渴望使用 sequelizejs 在模型定义上加载关联实体
【发布时间】:2013-12-21 18:56:00
【问题描述】:

我有一个用 SequelizeJS 定义的多对多关系,如下所示:

global.db.User.hasMany(global.db.Role, { as: 'UserRoles', joinTableName:'user_roles'});
global.db.Role.hasMany(global.db.User, { as: 'RoleUsers', joinTableName:'user_roles'});

我需要始终拥有已使用用户对象检索到的任何用户的角色。在为 User 定义模型时,而不仅仅是在调用 find 或 find all 时,有什么方法可以定义这种事情吗?

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    也许在定义模型时,您应该使用Getters & setters,以便自动查询user_role 表,就像这样:

    var User = sequelize.define('User', {
      name_field: { Sequelize.STRING },
      age_field: { Sequelize.INTEGER },
      // other fieds
      userRole: {
        type     : Sequelize.STRING,
        allowNull: false,
        get      : function()  {
          return global.db.Role.findOne({
            // user_id or how it defined in Role table    
            where: {user_id: this.userId}
          }).success(function(role) {
             return role 
          })
        }
      }
    });
    

    【讨论】:

    • 有趣,我会尽快尝试。我目前正在做一些工作,但这绝对值得研究。
    猜你喜欢
    • 2015-02-24
    • 2015-08-16
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2021-07-04
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多