【发布时间】:2016-01-30 11:35:25
【问题描述】:
我有 3 张桌子:
- 创作者
- 项目
- project_galleries
每个创建者都有一个项目列表,由他们的“creator_id”标识,即创建者表中的“id”,每个项目,如果它是“画廊”类型,将有一个由他们的“项目画廊”标识的列表。 project_id”是项目表中的“id”。
我想像这样输出一个json文件:
{
"creators" : [
name: "creator1",
projects: [
{
name: "project1",
type: "video" //no need to get project gallery here
},
{
name: "project2",
type: "gallery",
gallery_images: [
{
image: "01.jpg",
caption: "01 caption"
}
]
}
]
]
}
我可以用这个得到我需要的东西:
$this->db->select('*');
$this->db->from('1985_creators');
$this->db->join('1985_projects','1985_projects.creator_id = 1985_creators.id');
$this->db->join('1985_project_galleries','1985_project_galleries.project_id = 1985_projects.id','left');
$query = $this->db->get();
return $query->result_array();
我的控制器只是这样做:
$data['json'] = $this->creators_model->get_all_creator_data();
$this->load->view('data/json_data', $data);
这样的观点:
<?php
header('Content-type: application/json');
if(isset($json)) {
echo json_encode($json);
}
else {
echo json_encode(array('error' => true));
}
但是对于 json,我不需要“分组”——我只是得到了所有项目或画廊的列表。我将如何实现上面的 json 结构?我在文档中阅读了一些关于可能适用的编译选择的内容,但我不太确定如何使用它。或者也许我的控制器需要进行某种循环?
【问题讨论】:
-
我可以推荐使用由 Adrian Voicu 介绍并基于 Jamie Rumbelow 的 my_model 的 MY_Model。获取相关模型/表并从中获取数据的非常巧妙的方法。使用,它会返回你想要的结构数组。
标签: php mysql codeigniter join activerecord