Where in Join - Sequelize

1

Hello, I want to do a search inside 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 you do this query with Sequelize?

    
asked by anonymous 23.09.2016 / 22:06

2 answers

2

I will contextualize with 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 to the query itself where $OR is performed with both 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, there are several ways to do the same, more or less to the letter.

    
03.04.2017 / 19:30
0

After modeling your tables, use the include syntax, as per documentation .

    
01.11.2016 / 20:07