Laravel有很多通过与父母/孩子的关系

时间:2019-08-05 14:56:22

标签: laravel

我使用Laravel 5.5,并且有以下两个模型:ExerciceExerciceStudent

在我的Exercice模型中,我有以下关系:

public function exercicesStudents()
{
    return $this->hasMany('App\Models\ExerciceStudent');
}

public function exercicesChildren()
{
    return $this->hasMany('App\Models\Exercice', 'parent_id', 'id');
}

一个Exercice可以有几个ExerciceStudent和几个Exercice的孩子(使用Exercice模型中的parent_id字段)。

我希望能够将ExerciceStudent的数量Exercice进行计数,但是我希望拥有孩子的数量。

我尝试在我的Exercice模型中使用hasManyThrough:

public function exercicesStudentsByParent()
{
    return $this->hasManyThrough('App\Models\ExerciceEtudiant', 'App\Models\Exercice', 'parent_id');
}

我没有错误,但是计数:->withCount('exercicesStudentsByParent')始终为0。是否可以使用同一张表?

奇怪的是:->with('exercicesStudentsByParent')为我送回了正确的儿童学生。

0 个答案:

没有答案
相关问题