php - Laravel Eloquent: filtering model by relation table -


i have places , locations tables. place have many locations. location belongs place.

place: id title

location: id place_id floor lat lon

class location extends model {      public function place()     {         return $this->belongsto('app\place');     }  } 

and

class place extends model {      public function locations()     {         return $this->hasmany('app\location');     }  } 

and need find places, belongs 1st floor. select * places inner join locations on places.id = locations.place_id locations.floor = 1

how should done in eloquent?

is similar place::where('locations.floor', '=', 1)->get() exists?

yes, know there wherehas:

place::wherehas('locations', function($q) {     $q->where('floor', '=', 1); })->get() 

but generates bit complex query counts:

select * `places` (select count(*) `locations` `locations`.`place_id` = `places`.`id` , `floor` = '1') >= 1 

does not works?

class location extends model {      public function place()     {         return $this->belongsto('app\place');     }  }  $locations = location::where('floor', '=', 1); $locations->load('place'); //lazy eager loading reduce queries number $locations->each(function($location){      $place = $location->place     //this run each found location  });     

finally, orm not database usage optimization, , not worth expect nice sql's produced it.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -