问题
I'm implementing some tests to make sure my sequelize objects are saved correctly. I have a very simple schema: Article <--> Users
An Article is published by ONE User
A User can publish MANY Articles
Here is my Article model definition:
module.exports = function(sequelize){
"use strict";
var Sequelize = require('sequelize');
...
var Article = sequelize.define("Article", {
slug: {
type: Sequelize.STRING,
unique: true,
comment: "Unique URL slug to access the article"
},
title: {
type: Sequelize.STRING,
unique: true,
allowNull: false,
validate: {
notEmpty: true
}
},
summary: {
type: Sequelize.TEXT,
allowNull: true
},
body: {
type: Sequelize.TEXT,
allowNull: true
},
published: {type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true},
allowComment: {type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true}
}, {
freezeTableName: true,
classMethods: {
associate: function (models)
{
Article.belongsTo(models.User, {as: "Author", foreignKey: 'author_id'});
Article.hasMany(models.Comment, {as: "Comments", foreignKey: 'article_id'});
},
articlesForIndex: function()
{
return this.findAll({
where: {published: true},
order: 'createdAt DESC',
limit: 10
});
}
},
setterMethods : {
title : function(v) {
this.setDataValue('title', v.toString());
this.setDataValue('slug', slugify(v));
}
}
});
return Article;
};
What I want to do is forcing the Article
to have an Author
(User
). With the current definition I can create Article without Author
.
Here is my test that is failing:
module.exports = function (sequelize, models) {
'use strict';
var Q = require('q');
var should = require('chai').should();
describe('Article Model', function () {
describe('Validation', function () {
...
it('should not be valid without an author', function (done) {
models.Article.create({title: 'title5', summary: 'summary', body: 'body'})
.should.be.rejected.notify(done);
});
});
});
};
回答1:
On fairly recent (2.0-rc2 i believe) versions of sequelize you can change the foreign key to an object:
Article.belongsTo(User, {
as: "Author",
onDelete: 'CASCADE',
foreignKey: { name:'author_id', allowNull: false }
});
You also need to add onDelete: 'CASCADE'
because we can no longer set null on delete
来源:https://stackoverflow.com/questions/26835688/how-to-force-1n-association-with-sequelizejs