【问题标题】:Laravel 8: How to return questions that have answers by withCount()Laravel 8:如何通过 withCount() 返回有答案的问题
【发布时间】:2021-03-16 19:44:19
【问题描述】:

我正在使用 Laravel 8 开发我的论坛,我想返回有答案的问题。

所以我在我的方法中添加了withCount()

public function index()
    {
        $questions = Question::latest()->limit(5)->get();
        $topAnswered = Question::withCount('answers')->get();
        dd($topAnswered);
    }

所以$topAnswered 应该包含已经回答的问题,但它也会返回一些尚未回答的问题!

所以我需要解决这个问题,但不知道该怎么做......

请注意,我在 Question 模型中有这种关系:

public function answers()
    {
        return $this->hasMany(Answer::class);
    }

这个也是Answer 模特:

public function question()
    {
        return $this->belongsTo(Question::class);
    }

所以如果你知道如何只返回已经回答的问题,请告诉我,我将不胜感激。

提前致谢。

【问题讨论】:

    标签: php laravel eloquent laravel-8


    【解决方案1】:

    我认为您需要将 having 函数用作其中的另一个选择器

    $topAnswered = Question::withCount('answers')->having('answers_count', '>', 0)->get();
    

    【讨论】:

      【解决方案2】:

      你可以用whereHas做到这一点

      Question::whereHas('answers', function(Builder $query) {
         $query->where(...) //You condition where some questions that have not answered yet
      })->get();
      

      或者has:

      Question::has('answers', 0)->get();
      

      您可以阅读Laravel documentation的这一部分。

      【讨论】:

      • 我也喜欢这个答案。在 Laravel 和 Symfony 中处理数据有很多不同的方法,所以你只需选择一种可行的方法就可以了。
      【解决方案3】:

      我认为使用 has() 是最好的解决方案:

      public function index()
          {
              $topAnswered = Post::has('answers_count', '>', 0)->withCount('answers')->take(5)->get();
             
              dd($topAnswered);
          }
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-13
        • 1970-01-01
        • 2012-07-10
        相关资源
        最近更新 更多