我正在使用node v9.5和sequelize v4.33(postgres方言)。
我有两个一级模型:Driver
(特定的人)和Car
(通用的车型组合)。到目前为止,它们通过多对多的连接表进行连接。现在我想开始跟踪该连接表上的其他属性,但我在声明这些关系时遇到了问题,无法使它们正常工作。
const Driver = sqlz.define('Driver', {
id: { primaryKey: true, type: DataTypes.UUID },
name: DataTypes.string
})
const Car = sqlz.define('Car', {
id: { primaryKey: true, type: DataTypes.UUID },
make: DataTypes.string,
model: DataTypes.string
})
// old associations; worked great when requirements were simpler
Driver.belongsToMany(Car, {
through: 'DriverCar',
as: 'carList',
foreignKey: 'driverId'
})
Car.belongsToMany(Driver, {
through: 'DriverCar',
as: 'driverList',
foreignKey: 'carId'
})
现在我想要开始跟踪有关汽车及其驾驶员之间更多信息,例如特定汽车的颜色。
步骤1:我更新迁移脚本,向联接表添加一个新列,如下所示:
queryInterface.createTable( 'DriverCar', {
driverId: {
type: sqlz.UUID,
allowNull: false,
primaryKey: true,
references: {
model: 'Driver',
key: 'id'
}
},
carId: {
type: sqlz.UUID,
allowNull: false,
primaryKey: true,
references: {
model: 'Car',
key: 'id'
}
},
createdAt: {
type: sqlz.DATE,
allowNull: false
},
updatedAt: {
type: sqlz.DATE,
allowNull: false
},
// new column for join table
color: {
type: Sequelize.STRING
}
})
步骤2:我为DriverCar
定义了一个新的SQLZ模型:
const DriverCar = sqlz.define('DriverCar', {
color: DataTypes.string
})
我假设只需要定义有趣的属性,并且driverId
和carId
将仍然从将要被定义的关联中推断出。
步骤3:我需要更新Driver
、Car
和DriverCar
之间存在的关联。
这就是我卡住的地方。我尝试更新现有的关联,如下所示:
Driver.belongsToMany(Car, {
through: DriverCar, // NOTE: no longer a string, but a reference to new DriverCar model
as: 'carList',
foreignKey: 'driverId'
})
Car.belongsToMany(Driver, {
through: DriverCar, // NOTE: no longer a string, but a reference to new DriverCar model
as: 'driverList',
foreignKey: 'carId'
})
这段代码没有报错,但是当我尝试调用driver.getCarList()
时,并没有从连接表中获取到新的color
属性。(Sqlz被配置为记录每个SQL语句,我已经验证没有从连接表中请求任何属性。)
因此,我尝试更明确地定义这种关系,将Driver
与DriverCar
相关联,然后将Car
与DriverCar
相关联:
// Driver -> Car
Driver.hasMany(DriverCar, {
as: 'carList',
foreignKey: 'driverId'
})
// Car -> Driver
Car.hasMany(DriverCar, {
foreignKey: 'carId'
})
我还告诉sqlz DriverCar
不会有一个标准的行 id:
DriverCar.removeAttribute('id')
目前为止,请求 Driver 的车辆列表 (driver.getCarList()
) 似乎可以工作,因为我可以在 SQL 中看到联接表属性被提取。但是保存操作失败:
driverModel.setCarList([ carModel1 ])
UPDATE DriverCar
SET "driverId"='a-uuid',"updatedAt"='2018-02-23 22:01:02.126 +00:00'
WHERE "undefined" in (NULL)
错误:
SequelizeDatabaseError: column "undefined" does not exist
我认为这个错误的原因是sqzl不理解如何正确地识别连接表中的行,因为我没有建立必要的关联。而且说实话,我不确定我是否做得正确;我对ORM还很陌生,但我期望我需要指定4个关联:
Driver
->DriverCar
DriverCar
->Car
Car
->DriverCar
DriverCar
->Driver
简而言之,我有两个一级实体,它们在多对多的关系中连接。我试图向关系中添加数据,发现ORM需要以不同方式定义这些关联,并且在表达新关联时遇到麻烦。
include
方法行不通: https://github.com/sequelize/sequelize/issues/9094 - Tom