通过不处理存在枢轴的查询来排序 table laravel 8

order by not working on query where exists pivot table laravel 8

我有三个这样的 table :

ManyToMany关系。

模型产品:

Product_user(){
    return $this->belongsToMany(User::class, 'user_product', 'product_id', 'user_id');
}

模型用户:

User_product(){
    return $this->belongsToMany(Product::class, 'user_product', 'user_id', 'product_id');
}

查询 select 用户最喜欢的产品:

$toplike = Product::with('Product_user')
    ->whereExists(function ($query){
        $query->select('product_id', DB::raw('count(product_id) as total'))
            ->from('user_product')
            ->whereColumn('user_product.product_id', 'tbl_product.product_id')
            ->groupBy('product_id')
            ->orderBy('total', 'desc')
            ->take(10);
        })
    ->get();

我得到列表产品,但按总数排序不起作用,列表产品按 product_id 升序排序。

请帮帮我。

这将过滤关系而不仅仅是存在性检查:

$toplike = Product::with(['Product_user' => function ($query){
    $query->select('product_id', DB::raw('count(product_id) as total'))
        ->from('user_product')
        ->whereColumn('user_product.product_id', 'tbl_product.product_id')
        ->groupBy('product_id')
        ->orderBy('total', 'desc')
        ->take(10);
    })])
->whereExists(function ($query){
    $query->select('product_id', DB::raw('count(product_id) as total'))
        ->from('user_product')
        ->whereColumn('user_product.product_id', 'tbl_product.product_id');
    })
->get();