In laravel am using eloquent to get data from the database.
I have two tables 'questions' and 'options' Am using the eloquent method to join 'options' to 'questions'
$questions = Question::join('options', 'options.question_id', 'questions.id');
return QuestionResource($questions);
This does return an expected collection of data, where the same question appear multiple times in the collection and each is joined with different options where the 'options.question_id' and 'question.id' are the same.
[
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "city",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "planet",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "continent",
answer: true
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 2,
value: "comedian",
answer: false
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 1,
value: "genius scientist",
answer: true
}
]
I want all options be nested under a key within the related question. Like
[
{
id: 1,
text: "Africa is a...?",
// joined options
options: [
{value: "city", answer: false},
{value: "planet", answer: false},
{value: "continent", answer: true}
]
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined options
options: [
{value: "comedian", answer: false},
{value: "genius scientist", answer: true}
]
}
]
Can I achieve this with laravel's eloquent or I'll have to apply an extra logic.
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2fnZa1W
via IFTTT
Aucun commentaire:
Enregistrer un commentaire