【问题标题】:Laravel Eloquent 3 queries into oneLaravel Eloquent 3 查询合二为一
【发布时间】:2018-06-27 05:43:29
【问题描述】:

我想要实现的是一次执行 3 个查询,以限制 n1+ 问题:

假设我们有 3 个模型:

trips
  id => int
  price => float
  city_id => uint
........

cities
  id => int
  name => varchar
........

ratings:
  id => int
  ratable_id => int
  rate => small-int
......

伪代码:

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

所以结果是

[
  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 
]

我将如何做到这一点?

【问题讨论】:

    标签: php mysql laravel group-by laravel-5.6


    【解决方案1】:

    两种方法,使用 eloquent 方法(首选方法)或使用连接单个查询来获得所需的结果

    以雄辩的方式前进,我假设您已经根据它们的关系类型(1:m,m:m)定义了模型及其映射

    $trips= Trips::with('city')
                ->withCount('ratings')
                ->where('price', '>=', 100)
                ->get();
    

    与加入一起前进

    $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();
    

    【讨论】:

      【解决方案2】:

      出行模型关系

      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
      }
      

      获取数据

      $trips= Trip::with('city', 'ratings')
                  ->where('price', '>=', 100)
                  ->get();
      

      打印数据

      foreach($trips as $trip){
          $trip->city->name." - ". $trip->price." - ". $trip->ratings()->avg('rate');
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-21
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        • 1970-01-01
        • 2016-03-30
        • 1970-01-01
        • 1970-01-01
        • 2021-10-02
        相关资源
        最近更新 更多