I'm trying to show orders that belong to a certain seller when a customer place an order. The problem comes when a customer buys multiple products at once from different sellers.The order(including other products in cart) goes to the seller whose product is last in cart.
if the order is only one product everything seems to work. Here is how my query looks like in controller.
// 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);
}
Here is my user.php
public function sellerOrders()
{
return $this->hasMany(Order::class, 'seller_id');
}
Here is Order.php
public function user()
{
return $this->belongsTo('App\User', 'seller_id');
}
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity');
}
this is what is in product model
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');
}
Here is how my tables looks like https://imgur.com/a/2uF5iuS Any help would be appreciated.
Product.php
public function seller()
{
// a product belongs to a seller
return $this->belongsTo('App\User', 'seller_id');
}
So you would have an $order
and you can retrieve the order products like so:
$order->products()->with('seller')->get();
Using ->with('seller') will load in the sellers, and you use Eloquent's query builder
->groupBy('seller')` clause to group your results.