database - Sequelize field association does not work -
i have 2 tables. how link field in first table id
field in second table in sequelize?
first table:
tables.comments = sequelize.define('comments', { id: { type: sequelize.integer, primarykey: true, autoincrement: true }, text: sequelize.text, article: sequelize.integer, author: { type: sequelize.integer, references: "users", referenceskey: "id", allownull: false }, answer: sequelize.integer, rating: { type: sequelize.integer, defaultvalue: 0 } }, { classmethods: { associate: function(models) { tables.comments.belongsto(tables.models.users, {foreignkey: 'author', targetkey: 'name'}); } } });
second table:
tables.users = sequelize.define('users', { id: { type: sequelize.integer, primarykey: true, autoincrement: true }, mail: sequelize.text, name: sequelize.text, pass: sequelize.text, status: { type: sequelize.integer, defaultvalue: 0 }, rating: { type: sequelize.integer, defaultvalue: 0 }, ban: { type: sequelize.integer, defaultvalue: 0 }, key: sequelize.text }, { classmethods: { associate: function(models) { tables.users.hasmany(tables.models.comments, {foreignkey: 'author'}); } } });
i need tables.comments, instead of "author" name of author of tables.users. make request:
tables.comments.findall({inclide: [{model: tables.users}]}).then(function(comments) { console.log(comments); });
but in result in fields author
number, not name users
! mistake?
(sorry bad english)
in associate classmethod, you'll want use column name of table classmethod defined in. i'm assuming join condition comments.author = users.id
.
for comments table, be:
tables.comments.belongsto(tables.models.users, { foreignkey: 'author' });
for users table, be:
tables.users.hasmany(tables.models.comments, { foreignkey: 'id' });
Comments
Post a Comment