Codeigniter 2加入一对多查询3张表

Codeigniter 2 join one-to-many query 3 tables

我有 3 table

table1: documents (id, code, content)

table2: files (id, code, filename)

table3: tags (documentId, tag)

在我的页面上,我必须在 table 视图中显示所有文档。喜欢

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

您可以使用此查询,它会对您有所帮助

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` 

如果您有更多文件或文档标签,它将显示文档 table 中的一条记录,如果有多个

,标签和文件名将以逗号分隔

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

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

同时指定一个table,同时通过查询订购:

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

希望对您有所帮助?