我试图用简单的CRUD操作复制示例here。在此示例中我无法访问共享外键并进行设置。关于如何访问评论对象的“可评论”字段的任何建议?由于{constraint:false}(没有生成外键约束),它没有意义。
答案 0 :(得分:1)
以下是工作示例:
var Sequelize = require('sequelize');
var sequelize = new Sequelize(
'my_test', // db name
'postgres', // username
'postgres', // password
{
host: 'localhost',
dialect: 'postgres',
port:5432,
dialectOptions: {
ssl: false
},
logging: true, //verbose
pool: {
max: 5,
min: 0,
idle: 10000
}
}
);
// define models
var Image = sequelize.define('image', {
title: Sequelize.STRING
});
var Post = sequelize.define('post', {
title: Sequelize.STRING
});
var Comment = sequelize.define('comment', {
title: Sequelize.STRING,
commentable: Sequelize.STRING,
commentable_id: Sequelize.INTEGER
}
, {
instanceMethods: {
getItem: function() {
console.log(this);
console.log('====================');
console.log('====================');
//console.log(this.getTitle());
//console.log(this.getCommentable());
console.log('====================');
return this['get' + this.commentable.substr(0, 1).toUpperCase() + this.commentable.substr(1)]();
//where is the definition of this method? getImage/getPost.
}
}
}
);
// relations
// post-comment
Post.hasMany(Comment, { //adds fk in Comment
foreignKey: 'commentable_id',
constraints: false,
scope: {
commentable: 'post'
}
});
Comment.belongsTo(Post, { // fk on the src (Comment)
foreignKey: 'commentable_id',
constraints: false,
as: 'post'
});
// Image-comment
Image.hasMany(Comment, { //adds fk in Comment
foreignKey: 'commentable_id',
//as:'commentableId',
constraints: false,
scope: {
commentable: 'image'
}
});
Comment.belongsTo(Image, { // fk on the src (Comment)
foreignKey: 'commentable_id',
constraints: false,
as: 'image'
});
//=========
sequelize.sync()
.then(function () {
console.log('---------- sync');
var image1 = Image.build({title: 'very_important_task.jpg'});
var image1Promise = image1.save()
.then(function(i){
var commentPromise=i.createComment({ //create comment through image sets commentable and commentable_id
title: 'my comment 999999999'
});
// break the previous promise to be abel to access to image1 when we keep on adding to the chain
commentPromise
.then(function(c){ // now comment is saved.
console.log('##################### All comments: ');
image1.getComments()
.then(function(results){ //results[0] is the first result
console.log(
results.map(
function(item) {
return item['title']; //Or image.title item.commentable_id === image id
}
)
);
});
// after comment creation check accessing to comentable reference of this comment
c.getItem()
.then(function(i){
console.log(i.title)
});
});
//creat lots of comments
Comment.bulkCreate([
{title: 'my comment 1', commentable_id:image1.id, commentable:'image'},
{title: 'my comment 2', commentable_id:image1.id, commentable:'image'}
]).then(function() {
image1.getComments()
.then(function(results){
console.log(
results.map(
function(item) {
return item['title'];
}
)
);
});
});
}); //save promise of image to make sure it is created for any code accessing it
});