我的数据库结构:
人
id | name |
1 | John |
2 | Doe |
3 | Marc |
任务
task_id | task_name| person_id
1 | Get milk | 1
2 | Play cs | 1
3 | Walk dog | 2
4 | Eat fruit | 3
评论
id | comment | task
1 | Wich one | 1
2 | When? | 2
我试过这个:
function get_shapes2() {
$this->db->select('person.name,person.id,')
->select('GROUP_CONCAT(DISTINCT comments.id separator " -/r/- ") as "commentid" ')
->select('GROUP_CONCAT(DISTINCT comments.comment separator " -/r/- ") as "comment" ')
->select('GROUP_CONCAT(DISTINCT tasks.task_name separator " -/r/- ") as "tname"')
->select('GROUP_CONCAT(DISTINCT tasks.task_id separator " -/r/- " ) as "id2"');
$this->db->from('person');
$this->db->join('tasks', 'tasks.person_id = person.id', 'left');
$this->db->join('comments', 'comments.task = tasks.task_id', 'left ');
$this->db->group_by('id');
$query = $this->db->get();
$res = array();
foreach ($query->result() as $row) {
$posts[] = $row->name;
$posts[] = (int) $row->id;
$posts[] = array_map(function($tname, $tid){
return array('tname'=>$name,'tid'=>$tid);
},
explode(" -/r/- ",$row->tname),
explode(" -/r/- ",$row->id2));
array_push($res, $posts);
unset($posts);
}
return $res;
}
我得到的是:
{name: John, id: 1, task =[ {tname: "Get milk", tid: "1"},{tname: "Play cs", tid: "2"}]}
我要做的是为每个人完成所有任务,如果评论存在,则只有1个最新comment, comment_id
并将其存储在与任务相同的数组中
{name: John, id: 1, task =[ {tname: "Get milk", tid: "1" comment: " Wich one", commentid: 1 },{tname: "Play cs", tid: "2" comment: " When?", commentid: 2 }]}
我遇到的问题是我对如何做到这一点没有任何线索..
我已经尝试将其添加到array_map
,但它会随机存储评论,但没有找到工作
答案 0 :(得分:0)
请使用jquery来捕获json数据 - 这是很容易捕获的方法
$( document ).ready(function() {
$.getJSON("YOUR_PHP_LINK",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Name: " + value.name + "</td><td>ID: " + value.id+ " </td></tr>");
});
});
});
答案 1 :(得分:0)
Refer the below query
$this->db->select('*');
$this->db->from('comments');
$this->db->join('Tasks', 'comments.task=Tasks.task_id ', 'left');
$this->db->join('Person', 'Tasks.person_id=Person.id', 'left');
$this->db->where('comments.task', 1); //Provide id here...
$this->db->order_by("comments.id", "desc");
return $this->db->get()->result();