计算在Laravel中具有关系的关系

时间:2018-06-26 11:05:22

标签: php sql laravel eloquent

使用Laravel Eloquent ORM系统,我创建了以下模型:

/**
 * @property int $id
 */
class Category extends Model
{
    public function questions()
    {
        return $this->hasMany(Question::class);
    }
}

/**
 * @property int $id
 * @property int $category_id
 */
class Question extends Model
{
    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
}

/**
 * @property int $id
 * @property int $question_id
 */
class Answer extends Model {}

现在我正试图加载以下值:

  1. 所有类别
  2. 每个类别的问题数量
  3. 每个类别的已回答问题数量

我已经使用以下代码解决了1和2问题:

$categories = Category
    ::withCount('questions')
    ->get();

$vars = ['categories' => $categories];

对于第三个值,我尝试了类似的操作(不起作用):

$categories = Category
    ::withCount(['questions', 'questions as answered_questions' => function ($query) {
        $query->select()
            ->from('answers')
            ->whereRaw('answers.question_id = questions.id');
    }])
    ->get();

如何有效地计算出具有一个或多个答案的问题数量?

2 个答案:

答案 0 :(得分:1)

您可以尝试has

  

类别模型

class Category extends Model
{
    public function questions()
    {
        return $this->hasMany(Question::class);
    }

    function answers()
    {
      return $this->hasManyThrough(Answer::class, Question::class);
    }
}
  

获取数据

$categories = Category::withCount('questions')->has('answers')->get();

foreach($categories as $category){
  $category->name." - ". $category->questions_count;
}

这里questions_count是针对该类别的至少一个答案的总问题

答案 1 :(得分:1)

在@rkj的帮助下,我发现了has函数。这样我就可以创建以下解决方案:

$categories = Category
    ::withCount(['questions', 'questions as answered_questions' => function ($query) {
        $query->has('answers');
    }])
    ->get();

现在我可以使用$category->questions_count$category->answered_questions,这正是我所需要的。