【问题标题】:Why doesn't .add() insert value in the column?为什么 .add() 不在列中插入值?
【发布时间】: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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 那么 .add() 和 .save() 函数的用途是什么?他们实际上不是要插入数据吗?但虚拟存储?我做对了吗?
    • 这就是关联的工作方式。很多地方的数据都不一样。
    • 他们没有*相同的数据?
    • 不要储存。对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多