如何强制与Sequelizejs进行1:n关联 [英] How to force 1:n association with Sequelizejs
问题描述
我正在执行一些测试,以确保我的后继对象正确保存. 我有一个非常简单的模式:文章<->用户
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
这是我的Article模型定义:
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;
};
我要执行的是强制Article
具有Author
(User
).使用当前定义,我可以创建不带Author
的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
.
这是我的测试失败:
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);
});
});
});
};
推荐答案
在相当新的(sequelize)版本(2.0-rc2)中,您可以将外键更改为对象:
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 }
});
您还需要添加onDelete: 'CASCADE'
,因为我们不能再将delete设置为null
You also need to add onDelete: 'CASCADE'
because we can no longer set null on delete
这篇关于如何强制与Sequelizejs进行1:n关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!