我想知道是否有可能返回与LALAVILES路由模型绑定的关系?

比方说,有一个用户模型与其他用户有关系"朋友",我想从路由或控制器返回用户信息和关系.

eg f或 the route domain.tld/user/123

Route::model('user', 'User');

Route::get('/user/{user}', function(User $user) {

    return Response::json($user);

});

这会很好地返回我的用户信息,但我也想要关系,有什么简单/合适的方法可以做到这一点吗?

I know I can do this

Route::get('/user/{user}', function((User $user) {

    return Response::json(User::find($user['id'])->with('friends')->get());

});

Route::get('/user/{id}', function(($id) {

   return Response::json(User::find($id)->with('friends')->get());

});

but I suspect there may be a better way.

推荐答案

可以在用户模型中填充$with属性.像这样;

protected $with = ['friends'];

This will autoload the relationship data for you automatically.

Please Note: This will do it for every user model query.

If you dont want friends to be loaded all the time, then you can bind it to the parameter within your route, like so;

Route::bind('user_id', function($id) {
    return User::with('friends')->findOrFail($id);
});

Route::get('/user/{user_id}', 'BlogController@viewPost');

Laravel相关问答推荐

Laravel-如何按第三表关系对数据进行分类

我是否需要/是否可以从控制器运行LARLAVEL备份?

如何在 Laravel 中使用 return 停止 Trait php 的执行

嵌套数组请求的 Laravel 验证,其中如果整数之一为零,则另一个应大于零

如何提取每组 groupBy 查询的唯一值?

Laravel - 将变量从中间件传递到控制器/路由

Carbon(laravel)处理无效日期

laravel:如何在 Eloquent Query 中使用 LOWERCASE 函数?

在 Laravel 中无效后防止重定向到主页

Laravel 5 - Php artisan语法错误

Laravel Eloquent 在子查询中有两个WHERE NOT IN

控制器外部的 Laravel 访问请求对象

Laravel Eloquent 查询生成器默认 Where 条件

Laravel 存储链接不适用于生产

如何在 Laravel 中正确安装软件包?

Laravel Queue,Beanstalkd vs Database,有什么区别?

Laravel 4:将什么作为参数传递给 Url 类?

Mac OS X 需要 Mcrypt PHP 扩展

Laravel 5 - 从控制器级别的所有请求对象中删除参数

Laravel 仓库