Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias in Laravel Eager Loading

I need to alias when I do a Laravel eager loading:

$posts = Post::with(array('images as main_image' => function($query) // do not run
            {
                $query->where('number', '=', '0');

            }))
            ->where('id', '=', $id)
            ->get();

return Response::json($posts);

I need to to this because I want the JSON response like this:

[
  {
    "id": 126,
    "slug": "abc",
    "name": "abc",
    "created_at": "2014-08-08 08:11:25",
    "updated_at": "2014-08-28 11:45:07",
    "**main_image**": [
      {
        "id": 223,
        "post_id": 126
        ...
      }
    ]
  }
]

It is possible?

like image 652
kurtko Avatar asked Aug 28 '14 13:08

kurtko


People also ask

How eager loading works in laravel?

Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.

What is difference between eager and lazy loading laravel?

While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.

What is the benefit of eager loading when do you use it laravel?

Eager Loading: Eager Loading helps you to load all your needed entities at once. i.e. related objects (child objects) are loaded automatically with its parent object. When to use: Use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.


1 Answers

Perfect! you give me the idea. Finally I've done this:

Post.php

public function main_image()
{
    return $this->hasMany('FoodImage')->where('number','=','0');
}

public function gallery_images()
{
    // for code reuse
    return $this->main_image();
}

PostController.php

$posts = Post::with('main_image', 'gallery_images')                    
            ->where('id', '=', $id)                    
            ->get();
like image 65
kurtko Avatar answered Sep 25 '22 21:09

kurtko