【问题标题】:Laravel top sale product functionLaravel 顶级销售产品功能
【发布时间】:2021-10-10 09:17:43
【问题描述】:

我通过 order_details 在 Product 和 order 之间建立了多对多的关系,

我如何才能获得销量前 5 的产品?

产品:

public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_details');
    }

订单:

  public function products()
    {
        return $this->belongsToMany(Product::class, 'order_details')->withPivot(['quantity', 'sale_price']);
    }

数据透视表:

public function up()
{
    Schema::create('order_details', function (Blueprint $table) {
        $table->id();
        $table->foreignId('order_id');
        $table->foreign('order_id')
            ->on('orders')
            ->references('id')->onDelete('cascade');
        $table->foreignId('product_id');
        $table->foreign('product_id')
            ->on('products')
            ->references('id')->onDelete('cascade');
        $table->integer('quantity');
        $table->decimal('sale_price', 10, 4);
        $table->timestamps();
    });
}

【问题讨论】:

    标签: laravel eloquent many-to-many laravel-query-builder


    【解决方案1】:

    也许这样的事情会起作用

    $topfive = Order::with('products')->get()->sortBy(function($order) {
        return $order->products->count();
    })->take(5);
    

    在这里,您可以获取有任何产品的订单,从中收集,按每个订单拥有的产品数量排序,然后选择前 5 名。我希望这就是您所说的“前 5 名”。如果不告诉我并且我会修复查询。

    编辑 1

    由于您需要最常使用的产品,因此反向查询

    $topfive = Product::with('orders')->get()->sortBy(function($product) {
            return $product->orders->count();
        })->take(5);
    

    【讨论】:

    • 谢谢亲爱的,我想让前5名的销售产品显示在前端。
    • 那么这应该可以了。在查询后运行 dd($topfive) 并查看是否是您要查找的结果
    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多