Michael
Michael

Reputation: 405

How can I concat a relation in a Sequelize 'where'?

How can I combine two string columns from a relation in a where query? I have a table Car with a relation to the table Owner.

I tried the below, but it fails with the error

SequelizeDatabaseError: missing FROM-clause entry for table "carOwner"

  const result = Car.findAll({
    where: sequelize.where(
      sequelize.fn(
        'concat',
        sequelize.col('carOwner.firstName'),
        ' ',
        sequelize.col('carOwner.lastName'),
      ),
      {
        [op.iLike]: `%${query}%`,
      },
    ),
  })

Upvotes: 0

Views: 1126

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58533

I think you missed to include the associated model CarOwner :

Car.findAll({
    where: sequelize.where(
        sequelize.fn(
            'concat',
            sequelize.col('carOwner.firstName'),
            ' ',
            sequelize.col('carOwner.lastName'),
        ), {
            [op.iLike]: `%${query}%`,
        },
    ),
    include : {
        model : CarOwner , // <---- HERE
        required : true
    }
})

Upvotes: 1

Related Questions