简体   繁体   English

Laravel Eloquent 3个查询合而为一

[英]Laravel Eloquent 3 queries into one

What I'm trying to achieve is doing 3 queries in one go, to limit the n1+ problem : 我想要实现的是一次性执行3个查询,以限制n1 +问题:

given we have 3 models : 给定我们有3个模型:

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) 我以雄辩的方式向前迈进,我假设您已根据模型的关系类型(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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM