为什么.add()不在列中插入值? [英] Why doesn't .add() insert value in the column?

查看:90
本文介绍了为什么.add()不在列中插入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

我的桌子(1:驱动程序,2:汽车):

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


代码:

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

Driver.js

 module.exports = {
 connection: 'mysqlAdapter',
 tableName: 'driver',
 attributes: {
   id: {
     type: 'integer',
     primaryKey: true
   },
   Name: {
     type: 'string'
   },
   cars: {
     collection: 'car'
   }
 }
};

CarController.js

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


推荐答案

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

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

这篇关于为什么.add()不在列中插入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆