[英]Laravel: orderby count on pivot while filtering parent with keyword
Good morning everybody,大家早上好,
I have two tables, users
, questions
and one pivot table users_questions
.我有两张表,
users
, questions
和一张 pivot 表users_questions
。 A question belongs to many users.一个问题属于许多用户。 A user has many questions.
用户有很多问题。
users
-----
id | name
questions
---------
id | description
users_questions
---------------
user_id | question_id
I would like to get the top 3 users who asked the most questions for a specific keyword.我想获得对特定关键字提出最多问题的前 3 名用户。
To search a keyword inside a question, I use a simple filter package .为了在问题中搜索关键字,我使用了一个简单的过滤器 package 。 The code looks like that:
代码如下所示:
Questions::with('user')
->filter()
->paginate();
To get the 3 users who asked the most questions without filtering anything, I wrote this code:为了在不过滤任何内容的情况下获得提问最多的 3 个用户,我编写了以下代码:
UsersQuestions::with('user')
->select('mep_id')
->selectRaw('COUNT(*) AS count')
->groupBy('user_id')
->orderByDesc('count')
->limit(3)
->get();
But I can not figure out how to "mix" those two requests together.但我不知道如何将这两个请求“混合”在一起。
I was able to get the result I want by doing two queries: first getting the right results and then by filtering the pivot table with the previous ids.通过执行两个查询,我能够获得我想要的结果:首先获得正确的结果,然后使用以前的 id 过滤 pivot 表。
It is one way of doing it, but I'm not sure it is the best way.这是一种方法,但我不确定这是最好的方法。
$questions = Questions::with('users')
->filter()
->pluck('id')
->toArray();
return QuestionsUsers::with('users')
->whereIn('question_id', $questions)
->select('user_id')
->selectRaw('COUNT(*) AS count')
->groupBy('user_id')
->orderByDesc('count')
->limit(3)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.