简体   繁体   中英

Sequelize.js - Persist model with association

I'm trying to save an entity with the following models and save method but it only creates the parent entity. See:

var Project = database.define('projects', {
    name : {
        type : Sequelize.STRING,
        allowNull : false,
        unique : true
    },
    archived : {
        type : Sequelize.BOOLEAN,
        allowNull : false,
        defaultValue : false
    }
});

var Sprint = database.define('sprints', {
    name : {
        type : Sequelize.STRING,
        allowNull : false,
        unique : true
    },
    start : {
        type : Sequelize.DATE
    },
    end : {
        type : Sequelize.DATE
    }
});

Project.hasMany(Sprint, {
    as : 'sprints'
});
Sprint.belongsTo(Project);

The save method in Express:

var project = req.body;
models.Project.create(project).then(function(project){
    return res.json(project);
}, function(err) {
    return next(err); 
});

The req.body is something like:

{
    archived : false,
    name : "Projeto 1",
    sprints : [{
            end : "2016-02-25T03:00:00.000Z",
            name : "Sprint 1",
            start : "2016-02-19T02:00:00.000Z"
        }
    ]
}

The result is one record of Project created in database. Nothing more.
Sprint entry is also new, I was expecting it could be created together with Project.

Any ideas?

Thanks

Ok, now it saves Project and it's Sprints:

var project = req.body;
models.Project.create(project, {
    include : [{
            model : models.Sprint,
            as : 'sprints'
        }
    ]
}).then(function (project) {
    return res.json(project);
}, function (err) {
    return next(err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM