Sequelize有很多协会没有正常工作

时间:2016-03-04 08:52:15

标签: node.js sequelize.js belongs-to

我的代码有问题,我无法找到它的位置。 我在我的节点服务器上使用Sequelize。 好像我不能让belongsTo协会工作。

这是我从承诺中得到的错误:

  

[TypeError:对象的属性'setDetails'[对象   SequelizeInstance:car]不是函数]

实际上它的作用是插入详细数据但没有car_id,并且它不会在car table中插入数据。

这就是我所拥有的:

models / detail.js文件:

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

module.exports = Detail;

模型/ 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;

路由器/ 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关联,但不是这个。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

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

  

mickhansen:"您需要与您查询的一方的关系,以及之后的关系   你从汽车方面创造,你需要汽车 - >详情   。关系"

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

希望这有帮助。

相关问题