我有一个问题。在我的程序中,我需要有一个User
的集合,其中的另一个集合,所有项目都参与了用户,他在每个项目中工作的hours
数量。
我有3个表:
-
users
表格,prety简单。 -
projects
表。 -
time_entries
,带有user_id
和project_id
。
project
可以具有许多time_entries
和user
。
我有测试,但它不起作用:
$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;
}