Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

Laravel nested realtionsip with and withcout

I have a three table,

products, categories and product_categories,

i have below query to display the bestsellers,

$bestsellers = Product::has('bestselling', '>' , 0)->withCount(['bestselling as bestsellingproduct' => function($query) {

					$query->select(DB::raw('sum(quantity)'));

				}]) ->where('active_status',1)->orderBy('bestsellingproduct','DESC')->take(8)->get();

Product Model,

public function bestselling() {

        return $this->hasMany('App\OrderDetail');
    }

in order details there s a product_id column,

Now i want to fetch the bestsellers products category wise,

$categories = Category::withCount('Products')->with('Products.bestselling')->where('parent_id',0)->where('active_status',1)->orderBy('priority','ASC')->get(['id','slug','category_name','image']);

here i want to get fetch bestsellers based on bestselling order by DESC.

how to use nested relation for this? how to fetch details just like in first query in category?

0 likes
0 replies

Please or to participate in this conversation.