2016-07-11 3 views
1

私はPostgresでSequelizeを学んでいます。 「投稿」に複数の著者を含めるにはどうすればよいですか?私は現在、投稿あたり1人の著者しか持っていません。私はPost.hasMany(Person)を使ってみましたが、チュートリアルからコピーしたので、以下のsync文のデータをどのように記入するのか分かりませんでした。データベースを初めて使用しました。ネストされた関係、複数の「著者」を持つ「投稿」を後付けしますか?

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; 

答えて

2

試してみてください。

  Post.belongsToMany(Person, { 
       as: 'Authors', 
       through: 'post_authors', 
       foreignKey: 'id', 
       otherKey: 'id' 
      }) 
+0

私はこれらのエントリを追加する方法を疑問に思う:

Post.belongsToMany(Person); 

また、あなたが例えば中間のテーブルに名前を付けたい場合は、M2Mの詳細を指定することができます良い方法でこのpost_authorsテーブルに、私はこれを試みたが、多くはしない:http://i.imgur.com/y780UBl.png –

+0

私はまた、このスレッドを見ている:http:// stackoverflow。 com/questions/22958683/how-to-implement-many-to-many -association-in-sequelize –

関連する問題