【问题标题】:Codeigniter many-to-many relationship loopCodeigniter 多对多关系循环
【发布时间】:2013-01-24 08:03:38
【问题描述】:

我有一个这样的数据库设置:

post_id |标题

1 |一些标题

2 |另一个标题


tag_id |标记

1 |标签01

2 |标签02


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

【问题讨论】:

  • 这就是为什么 ORM 可以成为这样的 PITA。它们对于简单的事情很简单,为其他任何事情学习一个全新的知识领域。你最好学习如何使用连接。只是我的 2 美分。

标签: mysql codeigniter


【解决方案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');

【讨论】:

    【解决方案2】:

    如果您只想查找仅与单个帖子相关的标签,则需要使用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`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多