0
我使用Sequelize ORM和MySql,並且當前遇到了在表和輔助表中創建新條目的問題。 我的模型: 文章Sequelize - 將新行添加到表中並關聯表
module.exports = function (sequelize, DataTypes) {
var Articles = sequelize.define('articles', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
author: {
type: DataTypes.STRING
},
title: {
type: DataTypes.STRING
},
intro: {
type: DataTypes.TEXT
},
article: {
type: DataTypes.TEXT
},
cd: {
type: DataTypes.DATE
}
}, {
createdAt: 'cd',
updatedAt: false,
freezeTableName: true,
classMethods: {
associate: function (models) {
this.belongsToMany(models.comments, {
through: 'commented_articles'
});
}
}
});
return Articles;
};
Comments:
module.exports = function (sequelize, DataTypes) {
var Comments = sequelize.define('comments', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
id_parent: {
type: DataTypes.INTEGER,
defaultValue: null
},
user_id: {
type: DataTypes.INTEGER,
defaultValue: null
},
nick: {
type: DataTypes.STRING
},
title: {
type: DataTypes.STRING
},
comment: {
type: DataTypes.TEXT
},
plus: {
type: DataTypes.INTEGER,
defaultValue: null,
validate: {
isInt: {
msg: "Must be an integer number."
}
}
},
minus: {
type: DataTypes.INTEGER,
defaultValue: null,
validate: {
isInt: {
msg: "Must be an integer number."
}
}
}
}, {
createdAt: 'cd',
updatedAt: false,
freezeTableName: true,
classMethods: {
associate: function (models) {
this.belongsToMany(models.articles, {
through: 'commented_articles'
});
}
}
});
return Comments;
};
I want to add new comment to article, so probably my routing would look like
module.exports = function (app) {
var articles = require('./../apiMethods/articlesMethods');
app.post('/articles/:id/comments', articles.getSingleArticle);
};
I was trying to use addComment (http://docs.sequelizejs.com/en/latest/docs/associations/)
var models = require('../models'),
MyModel = require('../supportMethods/modelMethods'),
supportModel = new MyModel(models.articles);
module.exports = (function() {
return {
setArticle: function (req, res) {
models.articles.addComments(models.comments, {
user_id: req.body.user_id,
nick: req.body.nick,
title: req.body.title,
comment: req.body.comment
})
}
};
})();
The "commented_articles" is obviously automaticaly generated by squelize and contains article_id, comment_id and cd (row update timestamp).
我想才達到是將註釋添加到適當的文章,並在同一時間將在「commented_articles」新單元。 「評論」表包含對文章和圖片的評論(還有一個「commented_images」表)。 我試圖使用addComments方法,但它不起作用。我究竟做錯了什麼? 謝謝
我解決了我的問題: – camel