Sequelize hasMany 关联无法正常工作

Sequelize hasMany association not working properly

我的代码有问题,我找不到它在哪里。 我在我的节点服务器上使用 Sequelize。 看来我不能使 belongsTo 关联工作。

这是我从承诺中捕获的错误:

[TypeError: Property 'setDetails' of object [object SequelizeInstance:car] is not a function]

实际上它所做的是插入详细数据但没有 car_id 并且它不会在汽车 table.

中插入数据

这是我所拥有的:

models/detail.js 文件:

var Detail = pg.sequelize.define('details', {
        color: {
            type: pg.Sequelize.STRING,
            allowNull: false
        }
    }, {
        timestamps: false,
        underscored: true
    }
);

module.exports = Detail;

models/car.js

var Detail  = require('../models/detail');
var Car = pg.sequelize.define('cars', {
        id: {
            type: pg.Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        title: {
            type: pg.Sequelize.STRING,
            allowNull: false
        }
    }, {
        underscored: true
    }
);
var c = Detail.belongsTo(Car, {
    as: 'detail',
    foreignKey: 'car_id',
    onDelete: 'CASCADE'
});
Car.c = c;
module.exports = Car;

router/car.js

var Car  = require('../models/car');
router.post('/add', function(req, res, next) {

    var createData = {
        title: req.body.title,
        detail: {
            color: req.body.color
        }
    };

    Car.create(createData, { include: [ Car.c ] })
        .then(function(result) {
            res.status(200).json(result);
        })
        .catch(function(err) {
            console.log(err);
        });

});

module.exports = router;

我已经能够建立 hasMany 关联,但不能建立这个关联。

我的代码有什么问题?

我已经在 IRC 上得到了 mickhansen 的回答。

mickhansen: "you need the relationship for the side you query from, and since you're creating from the Car side, you need the Car -> Detail relation."

有道理。这里有一个例子: http://docs.sequelizejs.com/en/latest/docs/associations/#foreign-keys_1

希望对您有所帮助。