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?
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With