0

How do a query like:

SELECT agenda_id, data, count(*) FROM marcacoes group by data, agenda_id

I try $agendas = Marcacao::select(['data', 'agenda_id'])->groupBy('data', 'agenda_id')->count(); but the result is only the field count. The fields data and agenda_id is not showing.

3 Answers 3

2

You have to use a raw statement:

Marcacao::select('data', 'agenda_id', DB::raw('count(*)'))
    ->groupBy('data', 'agenda_id')
    ->get();
Sign up to request clarification or add additional context in comments.

1 Comment

See laravel.com/docs/queries#raw-expressions. It tells the query builder that count(*) is not the name of a column but a raw expression.
1

your request gives you just the number of agendas because you use count method.

if you want agandas data you request should be like this :

$agendas = Marcacao::select(['data', 'agenda_id'])->groupBy('data', 'agenda_id')->get();.

then when you want to get the number of your $agenda, you should just count $agandas collection like this :

$numberOfAgandas = $agandas->count();

Comments

1

Because you call the count method this will return just one value and int precisely which is the number of element that correspond to your MacMarcacao::select(['data', 'agenda_id'])->groupBy('data', 'agenda_id') you will not get all other fields because the count method return a value not a Collection like you are expecting.

You must firstly retrieve your record and after that you can count the method cound

$agendas = MacMarcacao::select(['data', 'agenda_id'])->groupBy('data', 'agenda_id')->get()

After that you can count number of records in your $agendas which is a an object of type Illuminate\Support\Collection

$numberOfAgendas = $agendas->count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.