php - Codeigniter Joins:基于连接查询的结果格式
问题描述
我在 db 部分和问题中有 2 个表,每个问题都有一个部分 id 作为 FK,我正在尝试获取部分和相关问题。下面加入查询让我得到结果
$result= $this->db->select('t1.*, t2.*')
->from('sections as t1')
->join('questions as t2', 't1.secid= t2.secid', 'LEFT')
->get();
print_r($result->result());
以下是我的结果以及与这些部分相关的所有部分和问题,
Array
(
[0] => stdClass Object
(
[secid] => 1
[secname] => Section 1
[secimg] =>
[qid] => 8
[qtext] => text
)
[1] => stdClass Object
(
[secid] => 1
[secname] => Section 1
[secimg] =>
[qid] => 9
[qtext] => test
)
[2] => stdClass Object
(
[secid] => 2
[secname] => Section 2
[secimg] =>
[qid] => 10
[qtext] => test
)
)
查询得到结果,但格式不正确。我希望结果中有 1 个部分,然后 1 个部分索引包含属于该部分的所有问题,如下所示。
[0] => stdClass Object
(
[secid] => 1
[secname] => Section 1
[secimg] =>
[question] => Array
(
[0] => stdClass Object
(
[qid] => 8
[qtext] => text
[secid] => 1
)
[1] => stdClass Object
(
[qid] => 9
[qtext] => test
[secid] => 1
)
)
)
有人可以帮助我如何使用连接来实现这一点
解决方案
你想要的不能只用连接来完成。您需要实际运行一个返回所有部分的第一个查询,然后为每个部分执行一个查询以获取问题。然后将每个部分的这些结果添加到第一个结果的另一个属性中。
$q = $this->db->get('sections');
$sections = $q->result();
foreach($sections as $key => $section) {
$sections[$key]->questions = $this->db
->where('secid', $section->secid)
->get('questions')
->result();
}
return $sections;
推荐阅读
- prolog - 将 shell 输出存储在变量中
- latex - IguanaTex 和 TikZ
- google-cloud-platform - GCP API Gateway 模型实现和输入验证
- encoding - 如何检查/读取二维码的编码
- r - 仅当整行相似时如何反加入
- azure - Azure 函数调用 exe 错误代码 216
- c# - 从 Entity Framework 6 日志中查看查询参数
- azure - 如何使用警报/powershell/cli 获取 Azure 活动日志摘要?
- android - OnNmeaMessageListener 不适用于三星 j7、android 6.0.1
- android - 如何在android的服务窗口中输入?