mysql 如何将此sql转换为squelize

c3frrgcw  于 2023-04-19  发布在  Mysql
关注(0)|答案(2)|浏览(145)

我需要通过两个字段连接另一个表,如何通过squelize得到这个

SELECT
    * 
FROM
    Issue
    LEFT OUTER JOIN File1 ON File1.project_id = Issue.project_id 
    AND File1.file_path = Issue.file_path 
WHERE
    Issue.project_id = 1 
    AND version_id =1

所以我试着用这个

class Issue extends Model<attributes, creationAttributes> {
    ...

  @BelongsTo(() => File1, {
    foreignKey: "project_id",
    targetKey: "projectId",
    constraints: false,
  })
  file!: File1;
}

Issue.findAll({
    where:{
        projectId:1,
        versionId:1
    },
    include:[File1]
})

但这段代码翻译成sql是

SELECT
    * 
FROM
    Issue
    LEFT OUTER JOIN File1 ON File1.project_id = Issue.project_id 
WHERE
    Issue.project_id = 1 
    AND version_id =1

这不是我想要的

rmbxnbpk

rmbxnbpk1#

你可以试试

Issue.findAll({
    where:{
        projectId:1,
        versionId:1
    },
    include:[{
      model: File1,
      as: 'File1',
      where: {
        file_path: '$Issue.file_path$',
      }
    }]
})

或者你可以参考这些文档:https://sequelize.org/docs/v6/advanced-association-concepts/eager-loading/#eager-loading-filtered-at-the-associated-model-level

lg40wkob

lg40wkob2#

受@SayedKhaidirAli的回答和文档启发,这很有用

Issue.findAll({
where:{
    projectId:1,
    versionId:1
},
include:[{
  model: File1,
  where: {
    file_path: { [Op.eq]: Sequelize.col("Issues.file_path") },
  }
}]})

相关问题