我正在尝试建立Places
和Rate
的INNER JOIN,但是我想设置一个“ custom” ON子句。它们之间的关系确实存在。
Place
模型的属性“ rate_code”上方有一个@ForeignKey(() => Rate)
,而Rate
模型的属性“ rate_code”上方有一个@ForeignKey(() => Place)
(此属性已编入索引,并且不是表PK),每当我创建 Place.findAll包括Rate 时,Sequelize都会生成类似SELECT ... FROM Place INNER JOIN Rate ON Place.id = Rate.rate_code
两个模型都包含一个未在模型上显示但会自动生成的PK,
模型/Place.ts
@Table
export class Place extends BaseModel<Place> {
@Column({
type: DataType.STRING,
allowNull: true,
defaultValue: null
})
name: string;
@ForeignKey(() => Rate)
@Column
rate_code: string;
@HasMany(() => Rate)
rate: Rate[];
}
model / Rate.ts
@Table
export class Rate extends BaseModel<Rate> {
@Column({
type: DataType.STRING,
allowNull: true,
defaultValue: null
})
name: string;
@ForeignKey(() => Place)
@Column({
type: DataType.STRING(10),
allowNull: true,
defaultValue: null
})
rate_code: string;
}
这是我生成序列化查询的方式: Service.ts
Place.findAll({
attributes: ['name', 'rate_code'],
include: [
{
model: Rate,
required: true,
attributes: ['name', 'rate_code'],
}
]
})
期望:
SELECT
Place.name,
Place.rate_code,
Rate.name,
Rate.rate_code
FROM Place
INNER JOIN Rate ON Place.rate_code = Rate.rate_code;
现实:
SELECT
Place.name,
Place.rate_code,
Rate.name,
Rate.rate_code
FROM Place
INNER JOIN Rate ON Place.id = Rate.rate_code;