简体   繁体   English

将预先存在的数据库上的多对多渴望加载序列化

[英]Sequelize Many-to-Many eager loading on pre-existing DB

I am attempting to setup my existing Express app with Sequelize. 我正在尝试使用Sequelize设置现有的Express应用程序。 In the application, upon a user logging in, I perform a query to try to obtain an object that represents the user and several of the relations from a handful of tables. 在应用程序中,在用户登录后,我执行查询以尝试从少数几个表中获取代表该用户以及几种关系的对象。 I have drawn my test down to the following minimized representation using a Many-to-Many relationship. 我已使用多对多关系将测试简化为以下最小化表示形式。

This is my User model (in coffeescript): 这是我的用户模型(在coffeescript中):

module.exports = (sequelize, DataTypes) ->
  sequelize.define "User",
    id:
      type: DataTypes.INTEGER(11)
      primaryKey: true
      autoIncrement: true

    email:
      type: DataTypes.STRING
      allowNull: false

  ,
    tableName: 'users'
    classMethods:
      associate: (models) ->
        @hasOne models.UserDetail
        @hasMany models.Plan,
          through: models.UserPlan
          foreignKey: 'user_id'

This is my Plan model: 这是我的计划模型:

module.exports = (sequelize, DataTypes) ->
  sequelize.define "Plan",
    id:
      type: DataTypes.INTEGER(11)
      primaryKey: true
      autoIncrement: true

    plan:
      type: DataTypes.STRING
      allowNull: false
  ,
    tableName: 'plans'
    classMethods:
      associate: (models) ->
        @hasMany models.User,
          through: models.UserPlan
          foreignKey: 'plan_id'

And, this is the intermediate 'through' table (user_plans): 而且,这是中间的“通过”表(user_plans):

module.exports = (sequelize, DataTypes) ->
  sequelize.define "UserPlan",
    user_id:
      type: DataTypes.INTEGER(11)
      allowNull: false
      primaryKey: true

    plan_id:
      type: DataTypes.INTEGER(11)
      allowNull: false
  ,
    tableName: 'user_plans'

Here is the find that I'm executing that I was hoping to get this working: 这是我正在执行的发现,希望能使它正常工作:

          console.log JSON.stringify(u)
          db.User.find(
            where:
              id: u.id
            include: [
                model: db.Plan
                as: 'plan'
            ]
          )
          .success (user) ->
            console.log JSON.stringify(user)

In this case, I have a non-eager loaded object 'u' that gets dropped to the console, but then post-query .success call never happens, so the 'user' object never gets dumped to the console. 在这种情况下,我有一个不急于加载的对象'u',该对象被丢弃到控制台,但是之后查询.success调用从未发生,因此'user'对象从未被转储到控制台。 Here is the output: 这是输出:

{"id":3,"email":"asdf@1234.com"}
[Error: Plan (plan) is not associated to User!]

Any idea what I could be doing wrong? 知道我做错了什么吗? Some poking around shows that this may have been a problem in the past with existing tables, but it looks like those problems have been resolved in the latest versions of sequelize. 一些证据表明,过去使用现有表可能是一个问题,但看起来这些问题已在最新版本的sequelize中得到了解决。 I am running ~1.7.0 (latest at the time of this writing). 我正在运行〜1.7.0(在撰写本文时为最新)。

Any help is appreciated. 任何帮助表示赞赏。

The as in includes specify an alias. as在包括指定别名。 This alias also has to be set when you set up the association. 设置关联时,也必须设置此别名。

A couple of examples: 几个例子:

User.hasMany(Plans) 
User.find({
  include: [
    { model: Plan }  // no as is allowed here, since we didnt specify it in the association
  ]
})

User.hasMany(Plans, { as: 'plans' }) 
User.find({
  include: [
    { model: Plan, as: 'plans' } // here you HAVE to specify the same alias as you did in your association
  ]
})

As a bit more advanced example, showing why the as is necessary, consider the same model being associated multiple times: 作为更高级的示例,说明为什么需要as,请考虑将同一模型多次关联:

User.belongsTo(Plans, { as: 'currentPlans' }) // this is joined via planId on user
User.hasMany(Plans, { as: 'previousPlans' }) // this is stored in a join table
Plan.hasMany(User)

User.find({
  include: [
    { model: Plan } 
      /* If you dont specify an as here, sequelize has no way of knowing which 
         relation to load. Therefore the as should only be provided if you 
         set one in the association, and you should provide the exact same
         string as in the assocation.
      */ 
  ]
})

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

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