2017-04-14 25 views
0

我試圖將產品模型與用戶模型關聯,同時確保強制同步以確保存在最新更改。我得到錯誤列UserId和ProductManagerId沒有創建。Sequelize Association列未生成

爲什麼不自動生成列?

Product.js

'use strict'; 
/* Model ONLY for DePuy Products */ 
module.exports = function(sequelize, DataTypes) { 
    var Product = sequelize.define('Product', { 
    name: { 
     type: DataTypes.STRING, 
     allowNull : false 
    }, 
    sku: { 
     type:DataTypes.STRING, 
     allowNull: false, 
     primaryKey: true, 
    }, 
    }, { 
    classMethods: { 
     associate: function(models) { 
     Product.belongsTo(models.User,{ as : 'ProductManager'}); 
     // associations can be defined here 
     } 
    } 
    }); 
     Product.sync({force: true}).then(() => { 
     console.log('Sequelize forced'); 
     }) 

    return Product; 
}; 

user.js的

module.exports = (sequelize, DataTypes) => { 
    const User = sequelize.define('User', { 
    id: { 
     type: DataTypes.INTEGER, 
     autoIncrement: true, 
     primaryKey: true, 
     allowNull: false, 
    }, 
    password: { 
     type: DataTypes.STRING, 
     allowNull: false, 
    }, 
    email: { 
     type: DataTypes.STRING, 
     unique: true, 
    }, 
    }, { 
    classMethods: { 
     associate: (models) => { 
     // associations can be defined here 
     User.hasMany(models.Product); 
     }, 
    }, 
    freezeTableName: true, 
    }); 
    // FORCE FOR NOW Use only if make model changes 
    User.sync({force: true}).then(() => { 
    console.log('Sequelize forced'); 
    }) 
    return User; 
}; 

方言:的Postgres Sequelize版本: 3.30.1

詩篇。我最初使用sequelize-cli生成模型文件,然後更改爲我的需要。

回答

0

我可能是錯的(或沒有充分了解),但這看起來像是一個bug。

在用戶模式:

// Note the addition of 'foreignKey' 
User.hasMany(models.Product, {as: 'ProductManager', foreignKey: 'ProductManagerId'}); 

在產品型號:

// Note the addition of 'foreignKey' 
Product.belongsTo(models.User,{ as : 'ProductManager', foreignKey: 'ProductManagerId'}); 

現在

在任何情況下,你可以通過在你的模型下面的小變化解決您的問題,你的產品表應該有一個FOREIGN KEY (ProductManagerId) REFERENCES user (id) ,你應該都準備好了。