245400
问题
2个表相关联,一定要在2个表中的定义associate吗, 如下user表,post表, 一个用户可以有多篇文章,一篇文章只能属于一个用户
app.model.User.hasMany(app.model.Post, { as: 'posts' });
app.model.Post.belongsTo(app.model.User, { as: 'user', foreignKey: 'user_id' });
user表
const User = app.model.define('user', {
id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: STRING(30),
age: INTEGER,
created_at: DATE,
updated_at: DATE,
});
User.prototype.associate = function() {
app.model.User.hasMany(app.model.Post, { as: 'posts' });
};
post
const Post = app.model.define('post', {
id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true,
},
title: STRING(30),
content: STRING(255),
user_id: INTEGER,
created_at: DATE,
updated_at: DATE,
});
Post.associate = function() {
app.model.Post.belongsTo(app.model.User, { as: 'user', foreignKey: 'user_id' });
};