我试图弄清楚如何从我的questions
表中获取“问题”,同时获取相应的answers
,或者在我的具体情况下,我已经将它们称为选择。 / p>
目前我是这样取的:
public static function getQuestion($id)
{
$sql = "SELECT * FROM questions WHERE id = :id";
$query = $database->prepare($sql);
$query->execute(array(':id' => $id));
if($query->rowCount() == 1){
return $query->fetch();
}
return false;
}
public static function getChoices($id)
{
$sql = "SELECT * FROM choices WHERE question_id = :id";
$query = $database->prepare($sql);
$query->execute(array(':id' => $id));
return $query->fetchAll();
}
所以我正在进行两(2)次查询,首先是我提出问题,然后我正在提取问题选择。 JSON格式的结果是:
{
"question": {
"id": "12",
"content": "asdasd",
"source": "asd",
"image_url": "156ebc3206212c_qijpmnklohgfe.jpeg",
"lastmodified": "2016-03-18 09:58:08",
"quiz_id": "6"
},
"answers": [
{
"id": "45",
"content": "Ja",
"correct": "0",
"question_id": "12"
},
{
"id": "46",
"content": "nej",
"correct": "0",
"question_id": "12"
},
{
"id": "47",
"content": "inte",
"correct": "0",
"question_id": "12"
},
{
"id": "48",
"content": "kanske ",
"correct": "1",
"question_id": "12"
}
]
}
但他“正确”的方式应该是答案(选择)嵌套在问题中:
{
"question": {
"id": "12",
"content": "asdasd",
"source": "asd",
"image_url": "156ebc3206212c_qijpmnklohgfe.jpeg",
"lastmodified": "2016-03-18 09:58:08",
"quiz_id": "6",
"answers": [
{
"id": "45",
"content": "Ja",
"correct": "0",
"question_id": "12"
},
{
"id": "46",
"content": "nej",
"correct": "0",
"question_id": "12"
},
{
"id": "47",
"content": "inte",
"correct": "0",
"question_id": "12"
},
{
"id": "48",
"content": "kanske ",
"correct": "1",
"question_id": "12"
}
]
}
}
如何加入(或急切加载)问题的选择?
答案 0 :(得分:0)
您可以编写第三个函数,使用连接来拉动它们。
$sql = "SELECT
q.id as question_id, q.content, q.source, q.image_url, q.lastmodified, q.quiz_id,
c.id AS answer_id, c.content as an_content, c.correct, c.question_id
FROM questions as q
INNER JOIN choices AS c ON q.id = c.question_id
WHERE q.id = :id";
答案 1 :(得分:0)
$database = DatabaseFactory::getFactory()->getConnection();
$question = Self::getFraga($id);
$answer = Self::getAnswers($id);
$question->answer = $answer;
return $question;
制作:
{
"question": {
"id": "12",
"content": "asdasd",
"source": "asd",
"image_url": "156ebc3206212c_qijpmnklohgfe.jpeg",
"lastmodified": "2016-03-18 09:58:08",
"quiz_id": "6",
"answer": [
{
"id": "45",
"content": "Ja",
"correct": "0",
"question_id": "12"
},
{
"id": "46",
"content": "nej",
"correct": "0",
"question_id": "12"
},
{
"id": "47",
"content": "inte",
"correct": "0",
"question_id": "12"
},
{
"id": "48",
"content": "kanske ",
"correct": "1",
"question_id": "12"
}
]
}
}
毕竟非常简单的解决方案