kur*_*tko 6 eager-loading laravel eloquent
当我做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);
Run Code Online (Sandbox Code Playgroud)
我需要这个,因为我想要这样的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
...
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
有可能的?
完美的!你给我出主意。最后我做到了:
后.php
public function main_image()
{
return $this->hasMany('FoodImage')->where('number','=','0');
}
public function gallery_images()
{
// for code reuse
return $this->main_image();
}
Run Code Online (Sandbox Code Playgroud)
后控制器.php
$posts = Post::with('main_image', 'gallery_images')
->where('id', '=', $id)
->get();
Run Code Online (Sandbox Code Playgroud)
use*_*496 -1
我不认为你可以用 Eloquent 来做到这一点,但有一些可能有效的解决方法。
如果您使用 PHP 5.6,则可以为该函数添加别名。
use function images as main_image;
Run Code Online (Sandbox Code Playgroud)
如果您使用的 PHP 版本低于该版本,您可以创建一个main_image()
函数并让它调用images()
.
public function main_image()
{
return $this->images();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4962 次 |
最近记录: |