Why doesn't .add() insert value in the column?

扶醉桌前 提交于 2019-12-20 07:37:44

问题


I'm trying sails.js association using one way reference (according to sails.js in action book). Now, the value of owner is successfully inserted in owner column, but value in cars column is not inserted.

When I tried console.log(foundDriver) and console.dir(foundDriver), it showed following things:

{ id: 1, Name: 'asdf' }

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

My tables (1: driver, 2: car):

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:


It will not be inserted because its 'virtual' data. When you want to get those data you need to join those 2 tables.

Driver.find({

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

});

Query sent to database will look more like this

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


来源:https://stackoverflow.com/questions/40818088/why-doesnt-add-insert-value-in-the-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!