Where em Join - Sequelize

Asked

Viewed 620 times

1

Hello, I want to do a search within several tables, for example:

SELECT * from tab1 
    INNER JOIN tab2 ON tab1.tab2_id = tab2.id 
    WHERE tab1.name LIKE '%blabla%' or tab2.title 
    LIKE '%blablabla%'

How would this query with Sequelize?

2 answers

2

I’ll put it in context with the models:

const Tab1 = sequelize.define('tab1', {
  name: sequelize.STRING,
  tab2_id: sequelize.INTEGER
})
const Tab2 = sequelize.define('tab2', {
  title: sequelize.STRING
})

// relacionamento

Tab1.belongsTo(Tab2, {
  foreignKey: 'tab2_id'
})

Now the query itself where the $OR is performed with the two tables:

return Tab1.findAll({
  where: {
    $or: [
      {
        name: {
            $like: '%blabla%'
        }
      },
      ['\`Tab2\`.\`title\`) LIKE ?', '%blablabla%'] // aqui é o macete
    ]
  },
  include: [
    Tab2
  ]
})

Sequelize does not deliver this kind of detail in the documentation but it is very customizable, has several ways to do the same, more or less to the letter.

0

After modeling your tables, use the syntax include, in accordance with documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.