skip to Main Content

i need join another table by two field like this,how to get this by 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

so I try to use this

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]
})

but this code translate to sql is

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

it’s not i want to get

2

Answers


  1. Chosen as BEST ANSWER

    inspired by @SayedKhaidirAli's answer and docs, this is useful

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

  2. You could try

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

    Or you could refer to this docs: https://sequelize.org/docs/v6/advanced-association-concepts/eager-loading/#eager-loading-filtered-at-the-associated-model-level

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search