代码之家  ›  专栏  ›  技术社区  ›  chinloyal

计算多对多关系的实例:Laravel

  •  0
  • chinloyal  · 技术社区  · 6 年前

    auth()->user()->userable->groups()->withCount('students') 但我知道了:

    对null调用成员函数getRelationExistenceCountQuery()

    经过编辑,以下是关系:

    # user model
    class User extends Authenticatable{
       public function userable(){
          return $this->morphTo();
       }
    }
    
    # staff/lecturer model
    Staff extends Model {
       public function user(){
           return $this->morphOne(User::class, 'userable');
       }
    
       public function groups(){
          return $this->hasMany(Group::class);
       }
    }
    
    #group model
    class Group extends Model {
       public function staff(){
          return $this->belongsTo(Staff::class);
       }
       public function students(){
          $this->belongsToMany(Student::class, 'groups_students', 'group_id');
       }
    }
    
    # student model
    class Student extends Model {
       public function groups(){
           return $this->belongsToMany(Group::class, 'groups_students', 'student_id');
       }
    }
    

    得到我想要的结果最有效的方法是什么?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Jonas Staudenmeir    6 年前

    Group::students() 正在丢失 return 声明:

    public function students(){
       return $this->belongsToMany(Student::class, 'groups_students', 'group_id');
       ^^^^^^
    }
    

    你可以得到这样的学生总数:

    $groups = auth()->user()->userable->groups()->withCount('students')->pluck('students_count');
    $count = $groups->sum();