I have a use case where I have some models (more than 20+) one of those models has relations with 15 other models, there are also some traits which have some appends in them.
I would like to get opinions on how should those queries run:
Sum some field on products table:
Should I use this syntacs:
$this->products()->sum('someField')
or should I use:
DB::table('products')->sum('someField')
It may be the same but I am not so sure, I am asking this because performance is very important and every ms save will be much appreciated. Thank you
Probably use DB::table()
The rule of thumb with Eloquent as well as any other ORM is that there is a lot of overhead in creating and "hydrating" objects, even worse if there are related tables with objects being queried and created. If all you need to do here is get a sum, then you avoid the overhead of the ORM.
With that said, the code to generate a sum should be similar in this case, if not a micro-optimization, because you are using a model class, so you're not hydrating an object or collection of objects.
You can always benchmark the two different approaches with your system/data. Either way you do it, sum is a SQL aggregate that's going to generate similar or exactly the same SQL and return you a number and not an object, where concerns about hydration and population of collections of related objects might be queried for by the ORM.