【发布时间】: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