我正在和Postgres学习Sequelize。如何让“帖子”拥有多位作者?我目前每篇文章只有一位作者。我尝试使用Post.hasMany(Person)
,但我无法弄清楚如何填写下面同步语句中的数据,因为我从教程中复制了它...这是我第一次使用数据库。
import Sequelize from 'sequelize';
import _ from 'lodash';
import Faker from 'faker';
const Conn = new Sequelize(
'test_db',
'postgres',
'postgres',
{
dialect: 'postgres',
host: 'localhost'
}
);
const Person = Conn.define('person', {
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
}
});
const Post = Conn.define('post', {
title: {
type: Sequelize.STRING,
allowNull: false
},
content: {
type: Sequelize.STRING,
allowNull: false
}
});
// Relationships
Person.hasMany(Post);
Post.belongsTo(Person);
Conn.sync({ force: true }).then(() => {
_.times(10, () => {
return Person.create({
firstName: Faker.name.firstName(),
lastName: Faker.name.lastName()
}).then(person => {
return person.createPost({
title: `Sample title by ${person.firstName}`,
content: 'This is a sample article.'
})
})
});
});
export default Conn;
答案 0 :(得分:2)
Try:
Post.belongsToMany(Person);
You can also specify more details about the M2M, if you wish to name the intermediary table for example:
Post.belongsToMany(Person, {
as: 'Authors',
through: 'post_authors',
foreignKey: 'id',
otherKey: 'id'
})