为什么.add()不在列中插入值?

时间:2016-11-26 11:58:32

标签: javascript node.js sails.js model-associations

我正在尝试使用单向引用的sails.js 关联(根据 sails.js in action 一书)。现在,所有者的值已成功插入所有者列,但未插入汽车列中的值。

当我尝试console.log(foundDriver)console.dir(foundDriver)时,它显示了以下内容:

{id:1,姓名:'asdf'}

{cars:[Getter / Setter],id:1,姓名:'asdf'}

我的表格(1:驱动程序,2:汽车):

enter image description here enter image description here

CODE:

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'
    }
  }
};

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});
                    });
            });
        });
    }
    };

1 个答案:

答案 0 :(得分:1)

它不会被插入,因为它的虚拟'数据。当您想要获取这些数据时,您需要加入这两个表。

Driver.find({

}).populate('cars').exec(function(error, drivers){

});

发送到数据库的查询看起来更像是

select * from driver inner join car where driver.id = car.owner