按外键字段数排序

Ordering by foreign key field count

我有三个 table 产品、用户和购买 table。我正在尝试 return 用户最常购买的产品类别列表。所以列表应该如下所示:Garden 4、Food 3、Sport 2 等

这是我的 table:

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

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

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

说明:

首先我们 select 当前用户购买的所有产品,然后我们将其与产品 table 合并,我们将我们的行与 类别 分组属性,在 we select 类别中,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()

检查这是否是您需要的:

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