在laravel am使用eloquent从数据库中获取数据。
我有两张桌子'问题'和'选项' 我正在使用雄辩的方法来加入“选项”。问题'
<?php
$a="hi";
$prints =" <html>
<h1> $a</h1>
</html>";
echo"$prints";
?>
这确实会返回预期的数据集合,其中同一个问题在集合中多次出现,并且每个数据都与不同的选项相关联,其中&#39; options.question_id&#39;和&#39; question.id&#39;是一样的。
$questions = Question::join('options', 'options.question_id', 'questions.id');
return QuestionResource($questions);
我希望所有选项都嵌套在相关问题中的键下。像
[
{
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
}
]
我可以用laravel的雄辩来实现这一目标,或者我必须应用额外的逻辑。
答案 0 :(得分:1)
如果你想申请额外的逻辑,这段代码可以帮助你
<?php
$combinedqst = array('id' => '','text'=> '','option'=> array('value' => array('value' => ,'' ), 'answer' => ''));
$ids = array('id' => , '');
//loop through questions array 1st loop for getting the question
foreach($questions as $question) {
$count = 0;
//check if question is already looped
if(!in_array($question["id"],$ids)){
//2end loop to get the opstions
foreach($questions as $question_check) {
if($question_check["id"] == $question["id"]){
if($count == 0){
$combinedqst["id"] = $question["id"];
$combinedqst["text"] = $question["text"];
}
$count = 1;
array_push($combinedqst["option"]['value'],$question_check['value']);
array_push($combinedqst["option"]['answer'],$question_check['answer']);
}
}
}
array_push($ids,$question["id"]);
}
vardump($combinedqst);