Codeigniter多对多关系循环

时间:2013-01-23 23:51:05

标签: mysql codeigniter

我有这样的数据库设置:

post_id |标题

1 |一些标题

2 |另一个标题


tag_id |标签

1 | tag01

2 | tag02


post_id | tagt_id

1 | 1

1 | 2

2 | 1

我已使用以下代码加入这些表:

$this->db->select('*');
$this->db->from('posts');
$this->db->join('posts_tags', 'posts.post_id = post_tags.post_id', 'inner');
$this->db->join('tags', 'posts_tags.tag_id = tags.tag_id', 'inner');

在我看来,我可以使用

访问该标记
$post['tag']

这会导致与其关联的每个标签都有重复的帖子。

问题是我如何循环浏览与一个帖子相关的所有标签?

预期输出为:

post_id 1 = tag01,tag02

而不是

post_id 1 = tag01

post_id 1 = tag02

2 个答案:

答案 0 :(得分:1)

如果您只想查找仅与单个帖子相关的标记,则需要过滤查询,以便仅使用WHERE子句查找您关注的帖子。

如果您的目的是返回所有帖子的所有标记,但每个帖子只有一行标记为逗号分隔值(或类似),则需要使用GROUP_CONCAT您的SELECT中的功能如下:

SELECT pt.post_id AS `post_id`, GROUP_CONCAT(t.tag) AS `tags`
FROM post_tags AS pt
INNER JOIN tags AS t ON pt.tag_id = t.tag_id
GROUP BY `post_id`

答案 1 :(得分:1)

试试这个

   $this->db->select('posts.post_id,GROUP_CONCAT(posts.tag) as all_tags');
   $this->db->from('posts');
   $this->db->join('posts_tags', 'posts.post_id = post_tags.post_id', 'inner');
   $this->db->join('tags', 'posts_tags.tag_id = tags.tag_id', 'inner');