简体   繁体   English

如何在Laravel 4 RESTful API中实现多对多关系

[英]How do implement many-to-many relationships in a Laravel 4 RESTful API

I'd like to implement something similar to what's asked in this question in Laravel 4, where a player/ resource can have more than one team/ , and vice-versa. 我想实现类似于Laravel 4中这个问题的要求,其中一个player/资源可以有多个team/ ,反之亦然。

In an ideal world I would be able to query 在理想的世界中,我将能够查询

players/1/teams

and get back some JSON like this: 然后像这样返回一些JSON:

{ player: { 
    id: 1, name: 'Bob', sport: 'Curling', teams: [
        { id: 1, name: 'Northern Curling Soc.', age: 2}, 
        { id:2, name: 'Southern Curling Soc.', age: 4 }
    ] 
}

or 要么

teams/{id}/players and get the correlative. teams/{id}/players并获得相关性。

Obviously if I were using Laravel's views I could simply call $player->teams and all would be well, but this is for a JSON API so it all needs to be up front. 显然,如果我使用Laravel的视图,我可以简单地调用$player->teams ,一切都会好起来的,但这是针对JSON API的,因此所有这些都需要预先准备。

I also need to be able to paginate the related results, although this is probably a different question. 我还需要能够对相关结果进行分页,尽管这可能是一个不同的问题。

How can I do this with Laravel? 我如何用Laravel做到这一点?

Thanks for any help! 谢谢你的帮助!

Laravel 4 added support for nested resources routes. Laravel 4增加了对嵌套资源路由的支持。 They're pretty nice, and seem perfectly suited for this. 它们非常好,并且似乎非常适合于此。

Basically, in addition to your "direct" resource controllers, you need to add routes for your nested resources. 基本上,除了“直接”资源控制器之外,您还需要为嵌套资源添加路由。 In this case, in addition to : 在这种情况下,除了:

Route::resource('players', 'PlayersController');  // players/#
Route::resource('teams', 'TeamsController');      // teams/#

... you'd need: ...您需要:

Route::resource('players.teams', 'PlayerTeamsController');  // players/#/teams/#
Route::resource('teams.players', 'TeamPlayersController');  // teams/#/player/#

Then in your controllers, methods that usually receives a single ID as parameter will now receive two (the order is defined by your route): 然后,在您的控制器中,通常将单个ID作为参数的方法现在将收到两个(顺序由您的路线定义):

class PlayerTeamsController extends Controller {

    public function show($player_id, $team_id) {

    }

}

You can then use inheritance to avoid code redundancy between your controllers. 然后,您可以使用继承来避免控制器之间的代码冗余。

Via the API, just include the relationship and return the object (in laravel 4). 通过API,只需包含关系并返回对象(在laravel 4中)。 L4 will automatically format the data for JSON output. L4将自动格式化数据以进行JSON输出。

return Player::with( [ 'teams' ] )->get();

It will give you pretty much exactly the format you're after :) 它会给您几乎完全一样的格式:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM