S
S
Sergey Rybakov2018-03-24 19:35:54
MySQL
Sergey Rybakov, 2018-03-24 19:35:54

How to select data from two tables using Sequelize?

I have been reading the documentation on Sequelize for several days now, but I just can’t make a selection from two tables that are associated with each other.
There are two tables:
users
+----+-------+
| id | name |
+----+-------+
| 1 | name1 |
| 2 | name2 |
+----+-------+
and
settings
+---------+-------+
| user_id | group|
+---------+-------+
| 1 |standard|
| 1 | Middle |
| 2 | Middle |
+---------+---------+
Tried to specify the relationship via
users.belongsTo(settings, {foreignKey: 'user_id', targetKey: 'id'})
and
users.belongsToMany( settings, { through: 'user_id' })
The sample was made through

Model.users.findAll({
  attributes: ['name'],
  where: {
    id: {
      [Op.in]: arUserID
    }
  },
  include: [{
    model: Model.settings,
    attributes: ['group']
  }]
})

The tables are declared as follows
Sequelize.define('settings',{ /* ... */ }, { tableName: 'settings'}

From the database I want to get the user name (from the `users` table) and his group (from the `settings` table), but in my options an incorrect query string is created and a non-existent field is added ( Unknown column 'settings.id' in 'field list' ) .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2018-03-24
@kyctarnik

settings.belongsTo(users); // в сеттингс появляется поле userId
Model.settings.findAll({
  include: [{
        model: Model.users,
        where:  {
           id: { [Op.in]: arUserID },
        },
   }],
});

user_id do not need to do it yourself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question