简体   繁体   中英

Sequelize MySql, get Questions and include Answers submitted by given user Id

I am using Sequelize with Mysql, in my Node.js application. I have designed a question and answer module where a user can answer a question and is stored in Question_Answers table. Question_Answers table has the question_id, answer, and user_id (the one who submitted the answer). I am trying to fetch all the Question including the answers by user_id.

data = await Questions.findAll({
        where: {
          status: 1,
        },
        include: [
          {
            model: Question_Answers,
            where: { user_id : 1 },
            attributes: [
              'id',
              'question_id',
              'answer',
              'user_id',
            ],
            as: 'answers',
          },
        ],
      });

Here if no answers is submitted by the user, even the question is not returned, but what I want is I still want to get question but answers can be empty object/list.

If I remove the where condition I will get all the answers, which is not posted even by that user_id.

How can I achieve this?

Works, when required = false is provided alongside the where condition.

data = await Questions.findAll({
    where: {
      status: 1,
    },
    include: [
      {
        model: Question_Answers,
        where: { user_id : 1 },
        attributes: [
          'id',
          'question_id',
          'answer',
          'user_id',
        ],
        required: false,
        as: 'answers',
      },
    ],
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM