musa
musa

Reputation: 1465

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?

Upvotes: 2

Views: 477

Answers (1)

jmserra
jmserra

Reputation: 1306

Well in this case i will opt for caching both tables in php associative arrays, and then loop just the arrays.

Upvotes: 0

Related Questions