sequelize中間テーブルマルチステート外部キー
3667 ワード
const Sequelize =require('sequelize')
const sequelize = new Sequelize(
'testdatabase',
'root',
'216612',
{
'dialect': 'mysql', // mysql
'host': 'localhost', // ip
'port': 3306, //
'define': {
// (_) ( )
'underscored': true
}
});
const ItemTag = sequelize.define('item_tag', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
tag_id: {
type: Sequelize.INTEGER,
unique: 'item_tag_taggable'
},
taggable: {
type: Sequelize.STRING,
unique: 'item_tag_taggable'
},
taggable_id: {
type: Sequelize.INTEGER,
unique: 'item_tag_taggable',
references: null
}
});
const Tag = sequelize.define('tag', {
name: Sequelize.STRING
});
const Post = sequelize.define('post', {
name: Sequelize.STRING
});
const Image = sequelize.define('image', {
name: Sequelize.STRING
});
Post.belongsToMany(Tag, {
through: {
model: ItemTag,
unique: false,
scope: {
taggable: 'post'
}
},
foreignKey: 'taggable_id',
constraints: false
});
Image.belongsToMany(Tag, {
through: {
model: ItemTag,
unique: false,
scope: {
taggable: 'image'
}
},
foreignKey: 'taggable_id',
constraints: false
});
Tag.belongsToMany(Post, {
through: {
model: ItemTag,
unique: false
},
foreignKey: 'tag_id',
constraints: false
});
Tag.belongsToMany(Image, {
through: {
model: ItemTag,
unique: false
},
foreignKey: 'tag_id',
constraints: false
});
let addTag=async ({name})=>{
let tag=await Tag.create({name})
return tag
}
let addPost=async ({name}) => {
let post=await Post.create({name})
return post
}
let addImage=async ({name})=>{
let image=await Image.create({name})
return image
}
sequelize.sync({force: true}).then(async function() {
let tag1=await addTag({name:"normal"})
let post1=await addPost({name:"post"})
let post2=await addPost({name:"post"})
let image1=await addImage({name:"image"})
let image2=await addImage({name:"image"})
//await tag1.addPost(post1,{through:{taggable:"post"}})
await post1.addTag(tag1)
//await tag1.addImage(image1,{through:{taggable:"image"}})
await image1.addTag(tag1)
//await tag1.addPost(post2,{through:{taggable:"post"}})
await post2.addTag(tag1)
//await tag1.addImage(image2,{through:{taggable:"image"}})
await image2.addTag(tag1)
return tag1
}).then(function(jane) {
console.log(jane.get({
plain: true
}));
});
ItemTag unique ;
id;
constraints: false
taggable_id
の を にします.この は であるため、REFERENCES
の のテーブルとは えません.
データの に await post1.addTag(tag1)
await tag1.addPost(post1,{through:{taggable:"post"}})
そうでなければtaggable_id ;
sequelizeを します.sync({force:true})データベースの