首页 > 解决方案 > 如何在laravel中排除不同卖家订单中的产品?

问题描述

当客户下订单时,我试图显示属于某个卖家的订单。当客户一次从不同的卖家那里购买多件产品时,问题就出现了。订单(包括购物车中的其他产品)转到最后一个产品在购物车中的卖家。

如果订单只是一种产品,一切似乎都有效。这是我的查询在控制器中的样子。

 // Seller Orders 
 public function viewOrders(User $user)
 {

 $orders = Auth::user()->sellerOrders()->products()->with('seller')- >orderBy('id', 'DESC')->paginate(2);
 // dd($orders);
 return view('orders')->with('orders', $orders);
 }

这是我的 user.php

 public function sellerOrders()
 {
     return $this->hasMany(Order::class, 'seller_id');
 }

这是 Order.php

public function user()
{
    return $this->belongsTo('App\User', 'seller_id');
}

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('quantity');
}

这就是产品模型中的内容

protected $table='products';
protected $primaryKey='id';
protected $fillable=  ['seller_id','pro_name','pro_price','pro_info','image','stock','category_id'];
}

 public function seller()
{
// a product belongs to a seller
return $this->belongsTo('App\User', 'seller_id');
}

这是我的表格的样子https://imgur.com/a/2uF5iuS 任何帮助将不胜感激。

标签: phplaravellaravel-5eloquente-commerce

解决方案


产品.php

public function seller()
{
    // a product belongs to a seller
    return $this->belongsTo('App\User', 'seller_id');
}

所以你会有一个$order,你可以像这样检索订单产品:

$order->products()->with('seller')->get();

使用->with('seller') will load in the sellers, and you use Eloquent's query builder->groupBy('seller')` 子句对结果进行分组。


推荐阅读