0

Schema: Media: id, mediable_id, mediable_type, name

Categories id, parent_id, name,

Articles id, title, description, author_id, and some other meta data fields

articles_categories article_id, category_id,

users id, name, email, pass

Relations:

  1. Articles and Categories: Many to Many

  2. Articles and Media: Polymorphic One to Many

  3. Categories to Media: Polymorphic One to Many
  4. Articles to Users: One to One

I tried various approach as suggested by damiani at Laravel - Eager Loading Polymorphic Relation's Related Models, but somehow I am not able to eager-load the media for the articles and categories.

$articles = Categories->with(array('user', 'media','articles' => function($query)
    {
        $query->where('articles.is_featured', '=', 1)
            ->where('articles.status', '=', 1)
            ->where('published_at', '>=', new \DateTime('today'))   
            ->orderBy('created_at', 'desc');

    }));

I also tried: $articles = Categories->with('articles', 'articles.media', 'articles.user');

Community
  • 1
  • 1
tanay jha
  • 349
  • 3
  • 11
  • Just add `articles.media` to the `with` array. – Jarek Tkaczyk Jan 22 '15 at 13:12
  • I had tried that already with no luck. – tanay jha Jan 22 '15 at 13:23
  • define `with no luck`. It's hard to help you if you don't tell us what you tried and what was the output vs. the output you expected. – Jarek Tkaczyk Jan 22 '15 at 13:26
  • Thanks Jarek! I read a bit more about it and found the expected result. There was no issue with the code but I was confusing between the JOIN and Eager loaded objects. I was just debugging the SQL output to see if the media table is being referenced but obviously that was the wrong approach. I get the articles objects in the `foreach` loop of ` $categories` , while to get the media related to an article I had to loop through the `$articles->media as $medias `. – tanay jha Jan 22 '15 at 13:57

1 Answers1

0

As suggested by Jarek and other stackoverflow users I needed to include another reference with the with static call, my code is:

$articles = Category::with(array('articles.media','articles' => function($query)
    {
        $query->where('articles.is_featured', '=', 1)
            ->where('articles.status', '=', 1)
            ->where('published_at', '<=', new \DateTime('today'))   
            ->orderBy('created_at', 'desc');

    }));    

And this is how I get the desired data:

foreach($categories as $category){
        echo "<hr>Category Information: ".$category->id."  :  ".$category->name;
        foreach($category->articles as $article){
            echo "--<br>Article ID is: ".$article->id;
            foreach($article->media as $media){
                echo "----<br>Image: ".$media->name;
            }
        }
    }

I hope I am using the correct solution.

tanay jha
  • 349
  • 3
  • 11