sequelize建立外键关系疑问
来源:6-14 深度应用 TS 解决当当书城复杂难题—构建符合前端的多表级联数据-第二阶段

慕粉3946981
2023-07-04
import { secondCtgyModel } from "./SecCtgyModel"; // 二级分类模型
import { thirdCtgyModel } from "./ThirdCtgyModel"; // 三级分类模型
// OneToMany 一对多
secondCtgyModel.hasMany(thirdCtgyModel, {
foreignKey: 'secctgyid', // thirdCtgyModel 模型中外键字段名
as: 'thirdctgy', // 查询 thirdCtgyModel 模型对应三级分类表对应数据字段前缀
})
// 一条 thirdCtgyModel 模型数据属性一条 secondCtgyModel 数据
thirdCtgyModel.belongsTo(secondCtgyModel, {
foreignKey: 'secctgyid', // thirdCtgyModel 模型中外键字段名
targetKey: 'secondctgyid', // 与 secondCtgyModel 模型中的 secondctgyid 主键建立关系
})
export default async function findSecThrdCtgysByFstCtgyId(firstctgyid: number) {
// 查询二级分类
const result = await secondCtgyModel.findAll({
where: {
firstctgyid
},
include: [
{
model: thirdCtgyModel, // 多表查询关联三级分类
as: 'thirdctgy', // 查询 thirdCtgyModel 模型对应三级分类表对应数据字段前缀
}
]
})
console.log('result', result)
return result
}
- 运行findSecThrdCtgysByFstCtgyId函数,在终端发现对应的sql语句是左外连接查询多表数据。可以让其通过内连接查询吗?(修改默认的左外连接查询)
- 在进行表一对多关联时可以修改外键策略吗?
- 请问上述代码对应的注释描述是否正确
1回答
-
问题1 :可以 ,增加 T1 行代码即可
async function findAllSecThrdCtgys() {
const result = await secondCtgyModel.findAll({
raw: true,
include: [
{
model: thirdCtgyModel,
as: 'thirdctgy',
required: true /** true 为 inner join false 为 left outer join */ T1
// nested: false
}
]
})
//console.log('result:', result)
}
问题2:有外键策略,一般外键策略多用于级联更新,级联删除等【数据表设置要相同】,可以在hasMany增加
onDelete: 'CASCADE', onUpdate: 'CASCADE', 然后应用upate操作 ,但需要和数据表统一。
注意的是:一般我们涉及到级联更新,删除,数据量稍大对性能损耗很严重,还有安全问题要考虑,企业一般都很少轻易使用,如果非要用,会采用原生 sql ,且数据量较小才使用,极少使用模型来操作,当数据量很大时,就会拆掉外键,提升性能。
另外可以这样些来控制外键是否为空: foreignKey:{field:'secctgyId',allowNull:false},【数据表设置要相同】
问题3:正确没问题
012023-07-04
相似问题