I am very new in Laravel and active records in general. I apologize in advance if this is a stupid question. But I would like to make sure if what I'm thinking is correct.
background:
The laravel docs says in the eloquent ORM section:
Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.
It has been mention many times that eloquent queries aren't very good when processing very large data, and it is usually a good idea to use the base query builder instead.
I am wondering about the statement:
You may use any of these methods in your Eloquent queries.
Many examples I've read separates the two (E.G.
DB::table('table')->get();
usually faster than
model::all()
) in comparing performance.
I am planning to create my new project with Laravel, and am thinking about using both functionalities (the base query builder methods for processing complicated and large data then using specific eloquent methods for anything else).
My question:
I'm thinking of how I can make my code readable, clean, and reasonably efficient. I would be dealing with possibly large data (E.G. thousands to millions of rows and 20 to 30 tables on two databases). Is it safe to say that:
DB::table('table')->get();
is the same as:
MODEL::get();
and assuming that both only return a collection, in large data usually faster than
MODEL::all();
? Thanks.
It's important to look at the differences of the return from each statement. While both will return a collection, it's the items in the collection that make the difference.
DB::table('table')->get()
Returns a collection of stdClass objects with no additional processing done by Laravel. If you are using SoftDeletes, this will ignore that functionality. It will also return all fields in the row.
MODEL::get()
This returns a collection of MODELs. Laravel will load each result into a new instance of MODEL. Traits like SoftDeletes and properties like hidden[] and visible[] will be respected.
Depending on what exactly you are going to be doing with the data will probably be the deciding factor. If you're returning it in a response, you'll probably want to use the MODEL approach so traits and properties are respected. If you're processing the data returned for some other use, then the DB approach may be best.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments