如何强制1:n与Sequelizejs联系

时间:2014-11-10 02:07:00

标签: node.js mocha sequelize.js

我正在实施一些测试,以确保我的续集对象得到正确保存。 我有一个非常简单的架构:文章< - >用户

  

文章 ONE 用户发布   用户可以发布 MANY 文章

这是我的文章模型定义:

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拥有AuthorUser)。使用当前定义,我可以创建没有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);
            });
        });
    });
};

1 个答案:

答案 0 :(得分:8)

在相当近期(2.0-rc2我相信)版本的续集中,您可以将外键更改为对象:

Article.belongsTo(User, {
    as: "Author", 
    onDelete: 'CASCADE', 
    foreignKey: { name:'author_id', allowNull: false }
});

您还需要添加onDelete: 'CASCADE',因为我们无法再在删除

上设置null