What I'm trying to achieve is doing 3 queries in one go, to limit the n1+ problem :
given we have 3 models :
trips
id => int
price => float
city_id => uint
........
cities
id => int
name => varchar
........
ratings:
id => int
ratable_id => int
rate => small-int
......
pseudocode:
select from tours where price >= 100
-then from the result
select from cities where id in result.city_id as cities
select count from ratings where ratable_id in result.id as rates groupBy rate
so the result is
[
trips => list of the trips where price more than or equal 100
cities=> list of the cities those trips belongs to
rates => list of rating with it's count so like [1 => 5, 2 => 100] assuming that '1 and 2' are the actual rating , and '5,100' is the trips count
]
how would I achieve that?
Two ways to go, Use eloquent methods which is preferred approach or use joins a single query to get your desired results
Moving forward with eloquent way i assume you have defined your models and their mappings based on their type of relationship (1:m, m:m)
$trips= Trips::with('city')
->withCount('ratings')
->where('price', '>=', 100)
->get();
Moving forward with join
$trips = DB::table('trips as t')
->select('t.id', 't.price','c.name',DB::raw('count(*) as rating_count'))
->join('cities as c' ,'t.city_id', '=' , 'c.id')
->join('ratings as r' ,'t.ratable_id', '=' , 'r.id')
->where('t.price', '>=', 100)
->groupBy('t.id', 't.price','c.name')
->get();
Trip Model Relationship
public function city(){
return $this->belongsTo(City::class);
}
public function ratings(){
return $this->hasMany(Rating::class, 'ratable_id'); //assuming ratable_id is an id of trips table
}
Fetch Data
$trips= Trip::with('city', 'ratings')
->where('price', '>=', 100)
->get();
Print Data
foreach($trips as $trip){
$trip->city->name." - ". $trip->price." - ". $trip->ratings()->avg('rate');
}