我有3张桌子(这里简化)
用户
id,name,email
小组
id,name
team_user
team_id,user_id
我想发送API查询以返回用户ID所属的所有团队,以及该团队中的其他成员。我不想只返回userIds,而是希望用实际的用户数据填充数组,例如名称和电子邮件。
Route::get('/user/{id}/teams/', 'UserController@getTeams');
User.php(模特)
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
public function teams()
{
return $this->belongsToMany('App\Team', 'team_user', 'team_id', 'user_id');
}
}
Team.php(模特)
class Team extends Model
{
public function users()
{
return $this->belongsToMany('App\User', 'team_user', 'team_id', 'user_id');
}
}
TeamUser.php(模型)
class TeamMember extends Model
{
public function user()
{
return $this->hasOne('App\User');
}
public function team()
{
return $this->hasOne('App\Team');
}
}
UserController.php
class UserController extends Controller
{
public function getTeams($userId) {
return User::find($teamId)->teams()->get();
}
}
返回:
[
{
"id": 6,
"name": "P12",
"location": "Newbury",
"owner": 6,
"active": 1,
"created_at": "2017-12-20 10:18:00",
"updated_at": "2017-12-20 10:18:00",
"pivot": {
"team_id": 6,
"user_id": 6
}
},
{
"id": 4,
"name": "fwffewfffffff",
"location": "ffffffff",
"owner": 4,
"active": 1,
"created_at": "2017-12-19 19:56:27",
"updated_at": "2017-12-19 19:56:27",
"pivot": {
"team_id": 6,
"user_id": 4
}
}
]
但是,我还希望在这两个团队中包含其他用户的列表。使用他们的名字和电子邮件(来自users表),而不仅仅是user_ids。
这可以在不进行进一步单独查询的情况下实现吗?
答案 0 :(得分:1)
您将能够热切地加载关系并将它们附加到模型中。
使用点符号teams.users
,输出将包含附加到ID为$userId
的用户的所有团队的所有用户。
我已添加findOrFail
以确保在找不到用户时它会返回404。
class UserController extends Controller
{
public function getTeams($userId)
{
return User::with('teams.users')->findOrFail($userId);
}
}
这将返回用户并附加关系。
如果你想返回团队,你可以这样做:
class UserController extends Controller
{
public function getTeams($userId)
{
$user = User::with('teams.users')->findOrFail($userId);
// $user->teams will hold a collection of teams with their users
return $user->teams;
}
}
答案 1 :(得分:0)
尝试使用with()
检索不同表格中的字段,例如
class UserController extends Controller {
public function getTeams($userId) {
return User::find($userId)->with('teams')->get();
// return User::find($userId)->teams()->get();
}
}
如果您想从 team_members 数据库中选择特定列,您可以在with
中添加功能,例如
class UserController extends Controller {
public function getTeams($userId) {
return User::find($userId)->with(['teams' => function($query) {
$query->select('id', 'name');
}])->get();
}
}
答案 2 :(得分:0)
现在我用
解决了这个问题class UserController extends Controller
{
public function getTeams($userId) {
$teamWithMembers = [];
$teams = User::find($userId)->teams()->get();
foreach($teams as $team) {
$team->members = Team::find($team->id)->users()->get();
$teamWithMembers[] = $team;
}
return $teamWithMembers;
}
}