簡體   English   中英

將預先存在的數據庫上的多對多渴望加載序列化

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

我正在嘗試使用Sequelize設置現有的Express應用程序。 在應用程序中,在用戶登錄后,我執行查詢以嘗試從少數幾個表中獲取代表該用戶以及幾種關系的對象。 我已使用多對多關系將測試簡化為以下最小化表示形式。

這是我的用戶模型(在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'

這是我的計划模型:

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'

而且,這是中間的“通過”表(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'

這是我正在執行的發現,希望能使它正常工作:

          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)

在這種情況下,我有一個不急於加載的對象'u',該對象被丟棄到控制台,但是之后查詢.success調用從未發生,因此'user'對象從未被轉儲到控制台。 這是輸出:

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

知道我做錯了什么嗎? 一些證據表明,過去使用現有表可能是一個問題,但看起來這些問題已在最新版本的sequelize中得到了解決。 我正在運行〜1.7.0(在撰寫本文時為最新)。

任何幫助表示贊賞。

as在包括指定別名。 設置關聯時,也必須設置此別名。

幾個例子:

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,請考慮將同一模型多次關聯:

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