我正在尝试使用单向引用进行 sails.js 关联(根据sails.js in action一书)。现在,owner 的值已成功插入到 owner 列中,但 cars 列中的值尚未插入。
当我尝试 console.log(foundDriver)
和 console.dir(foundDriver)
时,它显示以下内容:
{ id: 1, 名称: 'asdf' }
{ 汽车:[Getter/Setter],id:1,名称:'asdf' }
我的表格(1:司机,2:汽车):
代码:
Car.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'
}
}
};
驱动程序.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});
});
});
});
}
};
最佳答案
它不会被插入,因为它是“虚拟”数据。当您想要获取这些数据时,您需要连接这两个表。
Driver.find({
}).populate('cars').exec(function(error, drivers){
});
发送到数据库的查询看起来更像这样
select * from driver inner join car where driver.id = car.owner
关于javascript - 为什么 .add() 不在列中插入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40818088/