sequelize BelongsTo与HasOne一对一关系应用

请您多多留言指教

1、belongsTo 一对一关系

例如:
第一个表: student学生表 ,属性有 id、name、sex、stu_info_id等(主表中有关联表外键)
第二个表: studentInfo 学生信息关联表:id、addr、email等
 
① model 创建关联
// 表联合关系配置
Student.associate = function() {
Student.belongsTo(app.model.StudentInfo, { foreignKey: 'stuId', targetKey: 'id' , as: 'studentInfo'})
}
 
② 联合查询
Student.findMany = async function (stuId, other) {
        return await this.findAll({
          where: {
            id : stuId,
            name: { [Op.like]: `%${other || ''}%` },
            ...isDeletedCondition(0, Op)
          },
          include: {
            model: app.model.StudentInfo,
            as: 'studentInfo',
            required: false,
            where: {
              ...isDeletedCondition(0, Op)
            }
          }
        })
      }
      
 
③ 调用接口返回结果
{
    "status":"OK",
    "statusCode":0,
    "data":[
        {
            "id":"307b9380-42e1-11e8-8c1b-a7d81cdfdd36",
            "name":"wangwu",
            "sex":"人妖",
            "isDeleted":0,
            "createdBy":"xxxx-xxx-xxx",
            "updatedBy":"xxxx-xxx-xxx",
            "createdAt":"2018-04-18T08:19:18.000Z",
            "updatedAt":"2018-04-18T08:21:16.000Z",
            "studentInfo":{
                "id":"42e172f0-42e7-11e8-9bf7-fb82f749ce6d",
                "stuId":"307b9380-42e1-11e8-8c1b-a7d81cdfdd36",
                "addr":"123456",
                "grade":"1",
                "birthday":"2018-04-18T00:00:00.000Z",
                "isDeleted":0,
                "createdBy":"xxxx-xxx-xxx",
                "updatedBy":"xxxx-xxx-xxx",
                "createdAt":"2018-04-18T09:02:46.000Z",
                "updatedAt":"2018-04-18T09:10:10.000Z"
            }
        }
    ]
 
 
详解:
Student.belongsTo(app.model.StudentInfo, { foreignKey: 'stuId', targetKey: 'id', as : 'studentInfo' })
 
1、belongsTo 中 Student为源模型,StudentInfo为关联表模型(即目标模型)
2、外键在Student中
3、foreignKey 指定为源模型中的属性,targetKey为目标模型属性
4、as 指定目标模型命名 ,例如结果中的studentInfo
 
 
 

2、hasOne 一对一关系 --> 使用

例如:
第一个表: student学生表 ,属性有 id、name、sex等
第二个表: studentInfo 学生信息关联表:id、stu_id, addr、email等 (关联表中有主表的外键)
 
① model 创建关联
// 表联合关系配置
Student.associate = function() {
Student.hasOne(app.model.StudentInfo, { foreignKey: 'stuId', targetKey: 'id', 'as': 'studentInfo' })
}
 
②联合查询、调用接口的结果集 , 与上雷同
 
详解:
Student.hasOne(app.model.StudentInfo, { foreignKey: 'stuId', targetKey: 'id', as : 'studentInfo' })
 
1、hasOne 中 Student为源模型,StudentInfo为关联表模型(即目标模型)
2、外键在StudentInfo中
3、foreignKey 指定为目标模型中的属性,targetKey为源模型中属性
4、as 指定目标模型命名 ,例如结果中的studentInfo
 
 
belongsTo与hasOne区别: 外键属性存在位置不同,foreignKey 指定源不同,targetKey 指定源不同
 
补充:两表关联查询(关联表指定非主键字段)使用:foreignKey, sourceKey

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章