如何强制1:n与Sequelizejs联系

max*_*022 2 mocha.js node.js 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;
};
Run Code Online (Sandbox Code Playgroud)

我想要做的是强制Article拥有Author(User).根据当前的定义,我可以创建文章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);
            });
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

Jan*_*ier 8

在最新的(2.0-rc2我相信)版本的sequelize中,您可以将外键更改为对象:

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

您还需要添加,onDelete: 'CASCADE'因为我们不能再在删除时设置null

  • 我同意你的意见,但请停止'加油'我们 - 我们几乎有2-4人参与该项目,试图跟上错误报告,功能请求和维护文档.非常欢迎您为文档做出贡献 - 它是在(GH repo)[github.com/sequelize/sequelize]托管,非常欢迎PRs :) (2认同)