如何在 Laravel Eager Loading 中别名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25549526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to alias in Laravel Eager Loading
提问by kurtko
I need to alias when I do a Laravel eager loading:
当我执行 Laravel 急切加载时,我需要别名:
$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:
我需要这样做,因为我想要这样的 JSON 响应:
[
{
"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?
有可能的?
回答by kurtko
Perfect! you give me the idea. Finally I've done this:
完美的!你给我出主意。最后我做到了:
Post.php
后.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
后控制器.php
$posts = Post::with:with('main_image')->with('gallery_images')
->where('id', '=', $id)
->get();
回答by user1669496
I don't think you can do that with Eloquent, but there would be a few work-arounds that might work.
我不认为你可以用 Eloquent 做到这一点,但会有一些可能有效的变通方法。
If you are using PHP 5.6, it's possible to alias the function.
如果您使用的是 PHP 5.6,则可以为该函数设置别名。
use function images as main_image;
If you are using a version of PHP less than that, you can create a main_image()
function and have it call images()
.
如果您使用的 PHP 版本低于该版本,您可以创建一个main_image()
函数并让它调用images()
.
public function main_image()
{
return $this->images();
}