按外键字段计数排序

时间:2019-02-21 16:05:38

标签: laravel laravel-5 laravel-5.5

我有三个表,分别是产品,用户和购买表。我正在尝试返回用户最常购买的产品类别的列表。因此列表应如下所示:花园4,食物3,运动2等。

这是我的桌子:

产品id, name, categories_id, price  类别:ID,类别 用户id, name
购买id, users_id, products_id

我正在努力研究如何做到这一点,这是我到目前为止所拥有的

Purchase::with('products')->where('purchases.users_id', '=', Auth::users->id())

2 个答案:

答案 0 :(得分:1)

说明:

首先,我们选择当前用户购买的所有产品,然后将其加入产品表,然后将行与 category 属性分组,然后在类别中选择COUNT(*)

实现:

Purchase::where("purchases.user_id","=",Auth::user()->id)
          ->join("products","products.id","=","purchases.product_id")
          ->join("categories","products.categories_id","=","categories.id")
          ->select('categories.category', DB::raw('count(*) as total'))
          ->groupBy('products.category')
          ->get()

答案 1 :(得分:0)

检查这是否是您需要的:

$categories = Category::join('products', 'products.category', '=', 'categories.id')
->join('purchases','purchases.products_id', '=','products.id')
->select('categories.*')
->groupBy('purchases.product_id', 'categories.id')
->orderBy(\DB::raw('count(*) as product_purchase_count'), 'desc')
->get();