Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent Relationships Optimize Query

I have the following models: CardBoard, User, UserPricingPlans, PricingPlanLimits

Note: Don't mind if there is something wrong with the models code.They are working fine.

CardBoard

class CardBoard extends Model{

   public function user(){

      return $this->belongsTo('Models\User','id_user');

   }
}

User

class User extends Model{

   public function pricingPlans(){

      return $this->hasMany('Models\UserPricingPlan','id_user');

   }
}

PricingPlan

class PricingPlan extends Model{

   public function limits(){

      return $this->hasOne('Models\PricingPlanLimits','id_pricing_plan','id_pricing_plan');

   }
}

PricingPlanLimits

I'll not describe that Model, its not necessary for the problem. But keep in mind that there is an attribute called maxBoards.

The problem is that I only have the CardBoard Model Instance to work on and I want to get the maxBoard attribute from PricingPlanLImits. So I did it like this:

Note: I Already have the CardBoard Model Instance here!

$maxBoard = $cardBoard->user->pricingPlans->last()->limits->maxBoard;

return $maxBoard;

The code above runs great, but the number of queries generated by this operation is an overhead to me. Eloquent do an SELECT for every Relationship called and I don't want all these data and operations.

{
    "query": "select * from `users` where `users`.`id_user` = ? limit 1",
    "bindings": [
    ],
    "time": 0.96
}   
{
    "query": "select * from `users_princing_plan` where `users_princing_plan`.`id_user` = ? and `users_princing_plan`.`id_user` is not null",
    "bindings": [
    ],
    "time": 0.8
}
{
    "query": "select * from `pricing_plan_limits` where `pricing_plan_limits`.`id_pricing_plan` = ? and `pricing_plan_limits`.`id_pricing_plan` is not null limit 1",
    "bindings": [

    ],
    "time": 0.88
}

Isn't there an way to optmize this and run fewer queries in a Eloquent-Way ?

like image 477
Igor Morse Avatar asked Jun 13 '17 07:06

Igor Morse


People also ask

Which is faster eloquent or query builder?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

Is eloquent slow?

Using eloquent is great because its have many cool features but when it come to the speed, it slightly slower than query builder because of ORM.


1 Answers

you can get a data in one query if you use with() method.

for example: CardBoard::with('user.pricingPlans')->get();

so can optimize your query using with method.

like image 147
Shailesh Ladumor Avatar answered Oct 26 '22 01:10

Shailesh Ladumor