//Eloquent relationship
$customer = App\Customer::find($id); //1s query
return $orders = $customer->orders(); //2nd query
class
public function orders() {
return $this->hasMany('App\Order', 'customer_id')->get();
}
//Query builder, only query once
$data = DB::table('customers')
->select('orders.name...')
->leftJoin('orders', 'customers.id', '=', 'orders.customer_id')
->get();
I'm currently learning laravel, I was wondering when I use relationship to do left join query, is it will query twice?
If so which is better for performance? query builder left join can save one query which is the one I usually go with
Query builder is better for performance.
https://blog.sriraman.in/laravel-eloquent-vs-fluent-query-builder/
I would say eloquent relations are much better because -
By Using two queries it simplifies the initialization of eloquent
models.
If you use join queries instead, there's a chance that two columns have the same name, for example, the id
. So, you would explicitly select the columns.
At the PHP
side, you would then unpack the values appropriately so they can be delegated to the correct eloquent
class. This would further increase the execution time and increase memory usage and not to mention code complexity.
You can indeed retrieve many records at once using Query Builder (or raw SQL), but the obvious downside is that you won't have the power of using a model class because the Query Builder returns arrays. As you may already know, models aren't supposed to just help you with queries; they are useful beyond that.
And as iCode said (that replied while I was typing this), you would ask yourself: "why don't Laravel just joins columns to only do one query and then create all the models?" Well, the query itself and the logic in PHP needed for this to work would be pretty complex and it's not worth it.
Finally, when Eloquent relationships save a lot queries is when you query a bunch of Customer
records along their Order
records: in such case, all orders are taken with just one query.