how do I do this query in Eloquent

1

How can I make this query in Eloquent?

select count(id) as NumeroPreguntas, user_id
from preguntas 
group by user_id 
order by NumeroPreguntas 
DESC Limit 10;

I tried

pregunta::groupBy('categoria_id')->get()

but it does not work, but if I disable the Strcit mode of laravel database, then it works but I do not want to do that.

if I do this

$res = Pregunta::where('user_id',2)->take(10)->get();

$res = $res->GroupBy('categoria_id')

So if it works, but the problem is that I need to only take out the users that have asked the most questions. I just want to take the first 10

And I do not know how to do so that I take 10 with more questions. Since the above sql code does work but in Eloquent I do not know how.

    
asked by Alex Burke Cooper 03.11.2018 в 00:06
source

1 answer

1

Try the following way through queryBuilder() and step away from disabling the strict mode as you mentioned in your question

$data = \DB::table('preguntas')
        ->selectRaw('COUNT(id) AS NumeroPreguntas')
        ->select('user_id')
        ->groupBy('user_id')
        ->orderBy('NumeroPreguntas', 'ASC')
        ->take(10)
        ->get();

Since within the orderBy() method it already indicates that it is a ASC order to imitate the LIMIT instruction, it is enough to use the take() method and indicate the x number of records to be taken

    
answered by 03.11.2018 / 00:16
source