codeigniter 如何从数据库中提取数据

ppcbkaq5  于 2023-03-21  发布在  其他
关注(0)|答案(2)|浏览(176)

我的数据库结构:

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     | Which 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"}]}

我尝试做的是为每个人获取所有任务,如果comment存在,则仅获取1个最新的comment, comment_id,并将其存储在与任务相同的数组中

{name: John,  id: 1, task =[ {tname: "Get milk", tid: "1" comment: " Which one", commentid: 1 },{tname: "Play cs", tid: "2" comment: " When?", commentid: 2 }]}

我所面临的问题是我不知道该怎么做,我试过将它添加到array_map中,但它随机存储评论,似乎不起作用。

nwlls2ji

nwlls2ji1#

请使用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>");
            });
        });
});
eqfvzcg8

eqfvzcg82#

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();

相关问题