Home > Mobile >  How to write code to query sequelize model with where parameter in nested table
How to write code to query sequelize model with where parameter in nested table

Time:02-08

My database has a users, likes, dislikes, parcels table.

The likes, dislikes, parcels tables are linked to the users table by the user_id field, which is present in each of the linked tables.

How to sort likes in the users table that have deleted = false field values. If I make a request to the users model where

let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",          
    },
    {
      model: Dislikes,
      as: "dislikes",          
    },
    {
      model: Parcels,
      as: "parcels",          
    },
  ],
  where: {
    deleted: false,
  },
});

In this case, I get all the values ​​of the users table, where the field deleted = false.

    let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",
      where: {
        deleted: false,
      },
    },
    {
      model: Dislikes,
      as: "dislikes",
     
    },
    {
      model: Parcels,
      as: "parcels",
     
    },
  ],
  where: {
    deleted: false,
  },
});

The text of the request that sequelize generates

SELECT users.id_user, users.name_1, users.name_2, users.name_3, users.nation, users.citizenship, users.dateOfBirth, users.placeOfWork, users.education,
users.url_photo, users.deleted, likes.id_like AS likes.id_like, likes.id_user AS likes.id_user, likes.date AS likes.date, likes.deleted AS likes.deleted, dislikes.id_dislike AS dislikes.id_dislike, dislikes.id_user AS dislikes.id_user, dislikes.date AS dislikes.date, parcels.id_parcel AS parcels.id_parcel, parcels.id_user AS parcels.id_user, parcels.date AS parcels.date, parcels.deleted AS parcels.deleted FROM users AS users INNER JOIN likes AS likes ON users.id_user = likes.id_user AND likes.deleted = FALSE LEFT OUTER JOIN dislikes AS dislikes ON users.id_user = dislikes.id_user LEFT OUTER JOIN parcels AS parcels ON users.id_user = parcels.id_user WHERE users.deleted = FALSE;

In this case, I get only those records of the users table that have records in the likes table, respectively, all records in the user table and in the likes table have the field deleted = false.

However, I need to retrieve all records from the users table whether they have related records from the likes table or not. And also all records must have a field deleted - false

CodePudding user response:

I'm not sure that I got your question, but it seems that required: false is what you need:

let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",
      where: {
        deleted: false,
      },
      required: false,
    },
    {
      model: Dislikes,
      as: "dislikes",
     
    },
    {
      model: Parcels,
      as: "parcels",
     
    },
  ],
  where: {
    deleted: false,
  },
});
  •  Tags:  
  • Related