代码之家  ›  专栏  ›  技术社区  ›  Duncan Lukkenaer

数数在拉维里有关系的关系

  •  0
  • Duncan Lukkenaer  · 技术社区  · 7 年前

    使用laravel雄辩的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 回复  |  直到 7 年前
        1
  •  1
  •   rkj    7 年前

    你可以试试 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 是对该类别至少有一个答案的总问题

        2
  •  1
  •   Duncan Lukkenaer    7 年前

    在@rkj的帮助下我发现了 has 功能。有了它,我可以创建以下解决方案:

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

    现在 $category->questions_count $category->answered_questions 对我来说,这正是我所需要的。