【发布时间】:2016-11-26 11:58:31
【问题描述】:
我正在使用 单向参考(根据 sails.js in action 书)尝试使用sails.js association。现在,owner列中已经成功插入了owner的值,但是cars列中的值没有被插入。
当我尝试console.log(foundDriver) 和console.dir(foundDriver) 时,它显示了以下内容:
{ id: 1, Name: 'asdf' }
{汽车:[Getter/Setter],id:1,名称:'asdf'}
我的桌子(1:司机,2:汽车):
代码:
汽车.js
module.exports = {
connection: 'mysqlAdapter',
tableName: 'car',
attributes: {
id: {
type: 'integer',
primaryKey: true
},
Name: {
type: 'string'
},
Brand: {
type: 'string'
},
Model: {
type: 'string'
},
owner: {
model: 'driver'
}
}
};
Driver.js
module.exports = {
connection: 'mysqlAdapter',
tableName: 'driver',
attributes: {
id: {
type: 'integer',
primaryKey: true
},
Name: {
type: 'string'
},
cars: {
collection: 'car'
}
}
};
CarController.js
module.exports = {
createCars: function (req, res) {
Driver.findOne({
id: 1
}).exec(function (err, foundDriver) {
if (err) {
console.log("Err1" + foundDriver);
}
if (!foundDriver) {
console.log("Err2");
}
Car.create({
Name: "car1",
Brand: "brnd",
Model: "mdl",
owner: foundDriver.id
}).exec(function (err, createdCar) {
if (err) {
console.log("Err3");
}
foundDriver.cars.add(createdCar.id);
foundDriver.save(function (err) {
if (err) {
console.log(foundDriver);
}
return res.json({id: 100});
});
});
});
}
};
【问题讨论】:
标签: javascript node.js sails.js model-associations