如何在 Laravel Eager Loading 中别名 [英] How to alias in Laravel Eager Loading
本文介绍了如何在 Laravel Eager Loading 中别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在进行 Laravel 预加载时需要别名:
$posts = Post::with(array('images as main_image' => function($query)//不运行{$query->where('number', '=', '0');}))->where('id', '=', $id)->get();返回响应::json($posts);
我需要这样做,因为我想要这样的 JSON 响应:
<预><代码>[{身份证":126,"slug": "abc","name": "abc","created_at": "2014-08-08 08:11:25","updated_at": "2014-08-28 11:45:07",**main_image**":[{身份证":223,post_id":126...}]}]有可能吗?
解决方案
完美!你给我出主意.最后我做到了:
Post.php
公共函数 main_image(){return $this->hasMany('FoodImage')->where('number','=','0');}公共函数gallery_images(){//代码重用返回 $this->main_image();}
PostController.php
$posts = Post::with('main_image', 'gallery_images')->where('id', '=', $id)->get();
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?
解决方案
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();
这篇关于如何在 Laravel Eager Loading 中别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文