2

I have three tables a product, user and purchases table. I am trying to return a list of the category of products that the user has most frequently purchased. So the list should look like : Garden 4, Food 3, Sport 2 etc.

Here are my tables:

products: id, name, categories_id, price categories: id, category users: id, name
purchases: id, users_id, products_id

I am struggling to work out how to do this, this is what i have so far

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

2 回答 2

1

解释:

首先,我们选择当前用户购买的所有产品,然后将其与产品表连接,我们使用类别属性对行进行分组,并在我们选择类别中,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()
于 2019-02-21T17:54:04.640 回答
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();
于 2019-02-21T18:12:30.690 回答