1. 程式人生 > >One-To-One 一對一關係 BelongsTo與HasOne區別及使用

One-To-One 一對一關係 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' }) }② 聯合查詢 // 表聯合查詢
       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,
            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 指定目標模型命名 ,例如結果中的studentInfo2、hasOne 一對一關係 --> 使用例如: 第一個表: student學生表 ,屬性有 id、name、sex等第二個表: studentInfo 學生資訊關聯表:id、stu_id, addr、email等 (關聯表中有主表的外來鍵)① model 建立關聯 // 表聯合關係配置 Student.associate = function() { Student.hasOne
(app.model.StudentInfo, { foreignKey: 'stuId', targetKey: 'id' }) }②聯合查詢、呼叫介面的結果集 , 與上雷同詳解: Student.hasOne(app.model.StudentInfo, { foreignKey: 'stuId', targetKey: 'id', as : 'studentInfo' })1、hasOne 中 Student為源模型,StudentInfo為關聯表模型(即目標模型)2、外來鍵在StudentInfo中3、foreignKey 指定為目標模型中的屬性,targetKey為源模型中屬性4、as 指定目標模型命名 ,例如結果中的studentInfobelongsTo與hasOne區別 : 外來鍵屬性存在位置不同,foreignKey 指定源不同,targetKey 指定源不同