【问题标题】:Laravel count childs of a relationLaravel 计算关系的子节点
【发布时间】:2019-08-09 11:37:23
【问题描述】:

我在 Laravel 中有三个模型。

  • User
  • Profile
  • Rating

User 有很多 ProfilesProfile 有很多 Ratings

我的目标是获取用户拥有的评分总数。像这样的:

$user->profiles()->ratings()->count();

我怎样才能得到这个总数?

任何帮助将不胜感激,在此先感谢!

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您必须在用户模型中添加功能:

    public function profile()
    {
       return $this->hasMany('App\Models\Profile', 'user_id', 'id');
    }
    

    并在配置文件模型中添加功能:

    public function rating()
    {
       return $this->hasMany('App\Models\Rating', 'profile_id', 'id');
    }
    

    然后像这样调用:

    User::withcount('profile.rating'); 
    

    【讨论】:

      【解决方案2】:
      User::with('profiles.ratings')->count(); 
      

      应该做的伎俩

      你应该看看Nested Eager Loading

      【讨论】:

      • 这正是我想要的。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多