【问题标题】:How can I show the question that have the most answers by Eloquent如何显示 Eloquent 回答最多的问题
【发布时间】:2021-03-16 18:53:31
【问题描述】:

我正在使用 Laravel 8 开发我的论坛项目,在这个项目中,我有一个名为 questions 的表,其中包含已提出问题的数据,如下所示:

还有一个名为 answers 的表,其中包含基于 question_id 的这些问题的答案:

现在我想展示答案最多的问题。

我真的不知道如何使用 Eloquent 做到这一点,所以如果你知道请告诉我,我非常感谢你们的任何想法或建议......

提前致谢。

【问题讨论】:

  • 你有没有尝试过?您是否有QuestionAnswer 的模型以及它们之间的关系?请说明您尝试过的操作以及遇到的任何错误。
  • 您阅读手册了吗

标签: php laravel eloquent laravel-8


【解决方案1】:

您可以使用withCount,如以下文档所示:https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models。然后,您可以使用orderBy 按您想要的方式对它们进行排序。

【讨论】:

    【解决方案2】:
    $topAnswered = Answers::query()
                 ->select('*', DB::raw('count(*) as cnt'))
                 ->groupBy('answers.question_id')
                 ->orderBy('cnt')
                 ->get();
    

    【讨论】:

    • SQLSTATE[42000]: Syntax error or access violation: 1055 'dbname.answers.id' isn't in GROUP BY (SQL: select *, count(*) as cnt from answers` group by answers.question_id order by cnt asc)`
    • @tejoslaeslio select *, count(answers.id) as cnt from answers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多