【问题标题】:Get relation from table related to pivot with Eloquent使用 Eloquent 从与枢轴相关的表中获取关系
【发布时间】:2015-02-08 22:32:37
【问题描述】:

所以,我得到了 2 个模型,分别称为 TeamUser,其中 User 与多个 Teams 相关,而 Team 包含多个 Users。这意味着我有一个名为 team_user 的数据透视表。

我想从用户中获取团队成员。

我的关系设置如下:

// In the User model
public function teams()
{
    return $this->belongsToMany('App\Entities\Team');
}

// In the Team model
public function users()
{
    return $this->belongsToMany('App\Entities\User');
}

如何从用户返回团队中的用户?

我试过 User::find(1)->teams()->users() 但这不起作用..

我正在尝试返回这样的数组:

 [
   'teamName' => 'Team #1',
   'users' => [
      [
         'username' => 'John Doe'
      ], [
         'username' => 'John Doe #2'
      ]
   ],
   'teamName' => 'Team #2',
   'users' => [
      [
         'username' => 'Doe John'
      ], [
         'username' => 'Doe John #2'
      ]
   ]

【问题讨论】:

  • 大声笑我几乎尝试了所有东西.....除了@JoelHinz fml,谢谢!!
  • 没有汗水。我想我应该把它作为答案发布。 :) 一定是误删了评论,但我很高兴它有帮助。

标签: php laravel eloquent laravel-5


【解决方案1】:

首先,如果您的数据透视表名为 team_user 而不是 team_users,您必须在关系中指定它:

// In the User model
public function teams()
{
    return $this->belongsToMany('App\Entities\Team', 'team_user');
}

// In the Team model
public function users()
{
    return $this->belongsToMany('App\Entities\User', 'team_user');
}

然后您可以通过访问用户的teams()->get() 来检索团队并添加with('users') 以预先加载每个团队的users 关系:

$teams = User::find(1)->teams()->with('users')->get();

【讨论】:

  • 我想要用户 in 用户的团队。通过执行User::find(1)->teams()->with('users')->get()->toArray() 解决了它
  • 我的错,我的想法不正确。答案已更新:)
  • 我怎样才能在users 关系上设置位置,因为我不想在结果中拥有自己的user_id
  • 你可以通过急切的负载约束来做到这一点:laravel.com/docs/5.0/eloquent#eager-loading(向下滚动一点)
猜你喜欢
  • 2019-07-27
  • 2014-10-23
  • 2021-03-06
  • 1970-01-01
  • 2022-01-09
  • 2020-05-06
  • 2019-08-20
  • 1970-01-01
  • 2019-07-05
相关资源
最近更新 更多