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

 

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