Laravel 5.5,DB查询连接3个表,并按类别分组

时间:2018-04-25 05:51:08

标签: php laravel-5.5

我想要加入三个表,并按类别对它们进行分组。类似的东西:"西餐" =>卡车a,卡车b 目前,如果我有两辆相同类别的卡车,它没有显示结果,只显示一个。

tables:
touch_points: id, name

1 | starbucks

2 | kfc

3 | mcdonalds


t_categories: id, name

1 | western food

2 | chinese food

3 | indian food

truck_categories: id, touch_point_id, t_category_id

1 |  1 | 3

2 |  2 | 3

3 |  3 | 4

我现在的查询是:

 $truck = DB::table('truck_categories')
        ->join('touch_points', 'truck_categories.touch_point_id', '=', 'touch_points.id')
        ->join('t_categories', 't_categories.id', '=', 'truck_categories.t_category_id')
        ->select('t_categories.name', 'touch_points.id')
        ->groupBy('t_categories.name')
        ->get();

    return $truck;

提前致谢。

3 个答案:

答案 0 :(得分:0)

通过t_category_id

尝试此群组
$truck = DB::table('truck_categories')
        ->join('touch_points', 'touch_points.id' , '=', 'truck_categories.touch_point_id')
        ->join('t_categories', 't_categories.id', '=', 'truck_categories.t_category_id')
        ->select('t_categories.name', 'touch_points.id')
        ->groupBy('truck_categories.t_category_id')
        ->get();

    return $truck;  

答案 1 :(得分:0)

你可能会喜欢这个

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('follows', 'follows.user_id', '=', 'users.id')
    ->groupBy('currency_list')
    ->get();

有关详细信息,请参阅thisthis

答案 2 :(得分:0)

如果您想要放弃laravel编码标准,那么您应该使用如下的ORM:

  

=>对于 touch_points t_categories truck_categories 表,您已为此创建模型

     

=>然后,您需要设置与表父级和子级相关的关系。

     

=>与表结构相关,您需要在下面添加关系:

<强> truck_categories

class TruckCategory extends Eloquent{

  protected $table = 'truck_categories';  

  public function touchpoint()
  {
       return $this->belongsTo('App\TouchPoint'); // touch_points's model name.
  }
  public function tcategory()
  {
       return $this->belongsTo('App\TCategory'); // t_categories model name.
  }
}

<强> touch_points

class TouchPoint extends Eloquent{

  protected $table = 'touch_points';  

  public function truckcategory()
  {
       return $this->hasMany('App\TruckCategory'); // truck_categories's model name.
  }
}

<强> t_categories

class TCategory extends Eloquent{

  protected $table = 't_categories';  

  public function truckcategory()
  {
       return $this->hasMany('App\TruckCategory'); // truck_categories's model name.
  }
}
  

=&GT;然后数据从所有表中获取,分组为:

 App\TCategory::with('truckcategory')->get();