【问题标题】:How to have a collection in another collection?如何在另一个集合中有一个集合?
【发布时间】:2019-05-09 13:26:48
【问题描述】:

我有一个问题..在我的程序中,我需要有一个 User 的集合,这是另一个集合,其中包含用户参与的所有项目以及他在每个项目中工作的 hours 的数量。

我有 3 个表来解决这个问题:

  • users桌子,很简单。
  • 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();

【问题讨论】:

    标签: php laravel collections eloquent


    【解决方案1】:

    您可以使用Laravel EloquentUser/Project 模型之间定义Many-to-Many relationship

    /** 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;
    }
    

    【讨论】:

    • ``` $users = User::with('projects')->get(); foreach ($users as $user) { var_dump ($user->projects->name); } ``` 我不能有项目的名称。我的口才很差啊哈
    • 是的,你可以:$user->-first()->projects->first()->name;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2013-05-28
    相关资源
    最近更新 更多