2017-04-25 72 views
0

我有兩個模型,policyTablepolicy_rule定義如下。在policy_rule中有一列叫做policy_id,它是一個外鍵,在policyTable中對id列的引用。 policy_rule可以有多個policyTable,即有1:N的關係。續編簡單內連接

var policyTable = dbController.db.define('policyTable', { 
    id: { 
     type: Sequelize.BIGINT, 
     autoIncrement: true, 
     primaryKey: true 
    }, 
    't': { 
     type: Sequelize.BIGINT, 
     unique: true 
    }, 
    'name': { 
     type: Sequelize.STRING, 
    }, 
    src: { 
     type: Sequelize.STRING 
    } 
}, { 
    timestamps: false, 
    freezeTableName: true, 
    tableName: 'zo_policy', 
}); 

var policy_rule = dbController.db.define('policy_rule', { 
    policy_id: { 
     type: Sequelize.BIGINT, 
     references: { 
      model: policyTable, 
      key: 'id' 
     }, 
     onUpdate: 'cascade', 
     onDelete: 'cascade' 
    }, 
    agent_id: { 
     type: Sequelize.BIGINT, 
    }, 
    enabled: { 
     type: Sequelize.BOOLEAN, 
    } 
}, { 
    timestamps: false, 
    freezeTableName: true, 
    tableName: 'zo_policy_rule', 
}); 

現在我想加入這兩個模型,並獲得它們的所有列。我怎樣才能做到這一點?我想下面的代碼,但它說

Error: policy_rule is not associated to policyTable!

function getAllPolicies() { 
    return policyTable.findAndCountAll({ 
     include: [{ 
      model: policy_rule 
      }] 
    }).then(function (users) { 
     console.log(users); 
     data.count = users.count; 
     data.users = users.rows; 
     console.log(data); 
     return data; 
    }); 
}; 

回答

1

即使你的關聯是在數據庫級別定義,並指定此在列定義,使用sequelize的include功能,您還需要明確定義模型之間的關聯也是如此。

這裏是在DOCO的相關章節:http://docs.sequelizejs.com/en/latest/docs/associations/#belongstohttp://docs.sequelizejs.com/en/latest/docs/associations/#1m

在你的情況,這將意味着調整你的代碼沿以下線的東西 - 注意,每個模型定義新classMethods部分:

var policyTable = dbController.db.define('policyTable', { 
    id: { 
     type: Sequelize.BIGINT, 
     autoIncrement: true, 
     primaryKey: true 
    }, 
    't': { 
     type: Sequelize.BIGINT, 
     unique: true 
    }, 
    'name': { 
     type: Sequelize.STRING, 
    }, 
    src: { 
     type: Sequelize.STRING 
    } 
}, { 
    timestamps: false, 
    freezeTableName: true, 
    tableName: 'zo_policy', 
    classMethods: { 
     associate(models) { 
     this.hasMany(models.policy_rule, {foreignKey: 'policy_id'}) 
     } 
    } 
}); 

var policy_rule = dbController.db.define('policy_rule', { 
    policy_id: { 
     type: Sequelize.BIGINT, 
     references: { 
      model: policyTable, 
      key: 'id' 
     }, 
     onUpdate: 'cascade', 
     onDelete: 'cascade' 
    }, 
    agent_id: { 
     type: Sequelize.BIGINT, 
    }, 
    enabled: { 
     type: Sequelize.BOOLEAN, 
    } 
}, { 
    timestamps: false, 
    freezeTableName: true, 
    tableName: 'zo_policy_rule', 
    classMethods: { 
     associate(models) { 
     this.belongsTo(models.policyTable, {foreignKey: 'policy_id'}) 
     } 
    } 
});