Something is wrong with my code and I can't find where it is. I'm using Sequelize on my node server. It seems like i can't make belongsTo association work.
Here is the error I catch from the promise:
[TypeError: Property 'setDetails' of object [object SequelizeInstance:car] is not a function]
Actually what it does is INSERT the detail data but without the car_id and it does not INSERT data in car table.
And here is what I have:
models/detail.js file:
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;
I have been able to make an hasMany association but not this one.
What's wrong with my code ?
I've been able to have an answer from mickhansen on IRC about this.
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."
It make sense. There is an exemple here : http://docs.sequelizejs.com/en/latest/docs/associations/#foreign-keys_1
Hope this helps.