Reputation: 1335
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?
Upvotes: 0
Views: 143
Reputation: 1335
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',
},
],
});
Upvotes: 0