My question is, in instruction 1 I am running a select fulltable, returning all table columns and then passing to the Count() method to perform the count?
In this first code is returned 1 user of the type User
and with access to the cursos
and then the method count()
of classe
Collection is counted how many items have in this collection. Actually here are 2 SQL
, one retrieving the user and the other bringing the courses of that user (unnecessary reading). There’s a problem instead of you accessing the relationship, cursos()
is accessed to course collection (reading, from table data) and this is very wrong, there is no need at this time, when to use the data simply do:
$usuario = User::find(Auth::id());
$usuario->cursos()->count();
continues to be 2 SQL
, but at least does not load unnecessary table data.
And statement 2, it already mounts an sql that runs Count directly in the database returning only the total?
SQL
is direct, only 1 SQL
bringing the result per filter of the amount of courses, compared to 1 is direct and becomes better.
In short:
The second is more optimized and objective and in the first you take two turns, because,
Auth::id()
could be:
Auth::user()->cursos()->count();
since it is understood that the count of courses and the user logged in (or authenticated). In this line Auth::user()->cursos()->count();
is created 1 SQL
for course count as logged in user.
I understood, but by doing so "Auth::user()->courses()->Count();", eloquent mounts a Count sql, or returns all of that user’s data to later count?
– Fábio Jânio
@Fabio made some edits, and your doubt is in it, but, is 1 SQL that makes a filter as relationship with the user table and counts how many courses this user has, would be
select count(*) from cursos where userid = 1
, got it?– novic
Perfect. One last thing, I get a dump to see sql?
– Fábio Jânio
Auth::user()->cursos()->toSql()
for example quit SQL, I did other edits now I think it looks better, read item 1– novic
Very good. I was only in doubt in one part, when seeing sql, we can observe that it is a normal select. When chaining Count(), select is changed to a Count at the bank level or this count is due to an application method?
– Fábio Jânio
@Fabius is executed to
SQL
ofcount
by the call of the methodcount()
, which can be done correctly by accessing the methodcursos()
in that case aSQL
to the bank, other thancursos
which is what you said in the second part that is already the return of all courses that user (being more expensive and bad in this aspect of your application, ie in this case), do two tests that is ideal for you to understand:Auth::user()->cursos()
will return a Builder object (SQL construction summarizing) andAuth::user()->cursos
will return a Collection class full of data.– novic
Very good. I get it now. Thank you for sharing your knowledge Virgilio.
– Fábio Jânio