如何在另一个集合中拥有一个集合



我有一个问题。在我的程序中,我需要有一个User的集合,其中的另一个集合,所有项目都参与了用户,他在每个项目中工作的hours数量。

我有3个表:

  • users表格,prety简单。
  • projects表。
  • time_entries,带有user_idproject_id

project可以具有许多time_entriesuser

我有测试,但它不起作用:

$users = User::join('time_entries', 'users.id', '=', 'time_entries.user_id')
  ->whereBetween('spent_on', [($request->input('debut')), ($request->input('fin'))])
  ->join('projects', 'time_entries.project_id', '=', 'projects.id')
  ->selectRaw('user_id , project_id, sum(hours) as sum')
  ->get();

您可以使用Laravel Eloquent:

来定义User/Project模型之间的多对多关系
/** User.php */
public function projects()
{
    return $this
            ->belongsToMany(Project::class, 'time_entries')
            ->withPivot('hours');
}

-

/** Project.php */
public function users()
{
    return $this
            ->belongsToMany(User::class, 'time_entries')
            ->withPivot('hours');
}

然后访问关系:

/** UserController.php */
public function myFunction()
{
    $users = User::with('projects')->get();
    // this $users collection will have another collection inside (projects).

    $projects_of_first_user = $users->first()->projects;
}

相关内容

最新更新