简体   繁体   English

Codeigniter Datamapper多对多列表

[英]Codeigniter Datamapper many to many list

I have 2 many to many relationship tables; 我有2个多对多关系表; Posts and Categories. 帖子和类别。 One post can have many categories. 一个帖子可以有很多类别。 My question is how can I show list of posts with their categories? 我的问题是如何显示带有类别的帖子列表?

Like that: 像那样:

My post 1 (cat1, cat2, cat3) 我的帖子1(cat1,cat2,cat3)
My post 2 (cat2, cat3) 我的帖子2(cat2,cat3)
My post 3 (cat1) 我的文章3(cat1)

I've tried these methods; 我已经尝试过这些方法;

// Create post object
$p = new Post();

// Get 30 posts
$p->get(30);

// Loop through all posts
foreach ($p as $post)
{
    // Get the current user's group
    $post->category->get();

    foreach($post->category as $category) {
       // ...
    }
}

Don't like this, because if I'm get 30 posts, then on every post loop again make a query and find category again and again. 不喜欢这样,因为如果我得到30个帖子,那么在每个帖子循环上都再次进行查询并一次又一次地找到类别。

and tried this: 并尝试了这个:

$p = new Post();

$p->include_related('category', array('id', 'name'), TRUE, TRUE)->get(30);

foreach($p as $post) {
  // ...  
  foreach($post->category as $category) {
     // ...
  }
}

This is more close, but this one problem is I setting limit get(30) so if my per post have 2 categories than showing 15 post + 15 categories. 这更接近,但是这个问题是我设置了限制get(30)所以如果我的每个帖子有2个类别而不是显示15个帖子+ 15个类别。

What is the true method for many to many listing? 多对多上市的真正方法是什么?

在这种情况下,我将选择在php关联数组中缓存两个表,然后仅循环这些数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM