简体   繁体   中英

Codeigniter Datamapper many to many list

I have 2 many to many relationship tables; 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)
My post 2 (cat2, cat3)
My post 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.

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.

What is the true method for many to many listing?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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