Codeigniter 2加入一对多查询3表

时间:2018-05-29 08:33:33

标签: php mysql sql join codeigniter-2

我有3张桌子

table1: documents (id, code, content)

table2: files (id, code, filename)

table3: tags (documentId, tag)

在我的页面上,我必须在表格视图中显示所有文档。像

code | content

123 | This is a sample document with file **files.filename** and tags **tags.tag**

每个文档都可以有许多文件和标签

这是我目前的代码。

return $this->db
    ->select('t1.id, t1.barcode, t1.sub, t1.source_type, t1.sender, t1.address, t1.description, t1.receipient, t1.status, t2.id as fileId, t3.tag as docTag')
    ->select('DATE_FORMAT(t1.datetime_added, \'%m/%d/%Y-%h:%i %p\') as datetime_added', FALSE)
    ->from('documents as t1')
    ->join('files as t2', 't2.barcode = t1.barcode', 'left')
    ->join('tags as t3', 't3.id = t1.id')
    ->order_by('id', 'desc')
    ->get()->result_array();

2 个答案:

答案 0 :(得分:0)

您可以使用此查询来帮助您

SELECT `doc`.`id`,
       (select GROUP_CONCAT(`tag`) from `tags` `tag` where `docid`=`doc`.`id` group by `docid`) as `tags`, 
      (select GROUP_CONCAT(`filename`)  from `files` where `docid`=`doc`.`id` group by `docid`) as `file`
FROM `document` `doc` 

如果您有更多文件或文件标签,它将显示文件表中的一条记录,标签和文件名将以逗号分隔,如果多

答案 1 :(得分:0)

更改此行:->join('tags as t3', 't3.id = t1.id')

->join('tags as t3', 't3.documentid = t1.id') .

在查询订单时指定表格:

  ->order_by('t1.id', 'desc').

希望有帮助吗?