Laravel路线模型与关系的绑定 [英] Laravel Route model binding with relationship
问题描述
我想知道是否可以与laravels Route模型绑定返回关系吗?
I am wondering if it is possible to return a relationship with laravels Route model binding ?
说是一个具有与其他用户朋友"关系的用户模型,我想同时从路由或控制器返回用户信息和关系.
Say is a have a user model with a relationship 'friends' to other users, and I want to return both the user info and the relationship from a route or controller.
例如路线domain.tld/user/123
Route::model('user', 'User');
Route::get('/user/{user}', function(User $user) {
return Response::json($user);
});
这将向我返回用户信息,但我也希望建立关系,是否有任何简单/适当的方法?
this will return me the user info fine but I also want the relationships, is there any easy/proper way to 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
属性.像这样;
You can populate the $with
property in the User model. Like so;
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路线模型与关系的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!