1

I'm learning Sequelize with Postgres. How can I make the "post" to have multiple authors? I currently have only one author per post. I tried using Post.hasMany(Person) but I couldn't figure out how to fill in the data in the sync statement below, because I copied it from a tutorial... It's my first time using a database.

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;
Vlady Veselinov
  • 4,678
  • 5
  • 23
  • 49

1 Answers1

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'
            })
beansontoast
  • 181
  • 2
  • 12
  • I wonder how to add these entries to this post_authors table in a nice way, I tried this, but it doesn't do much: http://i.imgur.com/y780UBl.png – Vlady Veselinov Jul 11 '16 at 22:29
  • I'm also looking at this thread: http://stackoverflow.com/questions/22958683/how-to-implement-many-to-many-association-in-sequelize – Vlady Veselinov Jul 12 '16 at 01:07