【发布时间】:2019-07-10 17:34:19
【问题描述】:
我希望卖家能够删除/编辑他列出的产品。但是,如果该产品已由客户订购,我希望订单保持不变而不是更改。我怎样才能做到这一点?
现在当我更新/删除它会影响之前提交的订单。 这就是我现在删除产品的方式。
public function destroy($id)
{
$userId = Auth::user()->id;
$deleteData=product::where('seller_id', $userId)->findOrFail($id);
$deleteData->delete();
return redirect()->back();
}
订单.php
public function user()
{
return $this->belongsTo('App\User', 'seller_id');
}
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity','total','Subtotal');
}
public function orderItems()
{
return $this->hasMany('App\OrderProduct');
}
编辑:
Controller for seller orders
// Seller Orders
public function viewOrders(User $user)
{
//$seller = Auth::user();
$totals = OrderProduct::select("seller_id", DB::Raw("SUM(Subtotal) AS total"), 'order_id')
->where('seller_id', '=', \Auth::user()->id)
->groupBy('seller_id')
->groupBy('order_id')
->get();
$orders = Order::whereHas('orderItems.product', function ($query) {
$query->where('seller_id', '=', \Auth::user()->id);
})->orderBy('id', 'DESC')->withTrashed()->get();
return view('orders', ['orders'=> $orders, 'total'=> $totals] );
}
卖家刀片模板
@foreach ($order->orderItems as $item)
@if($item->product->user_id == Auth::user()->id)
<td>{{ $item->name }}</td>
<td>{{ $item->price }}</td>
@else
@endif
@endforeach
OrderProduct.php
class OrderProduct extends Model
{
use SoftDeletes;
protected $table = 'order_product';
protected $fillable = ['order_id', 'seller_id','product_id', 'quantity','Subtotal','total','name','price'];
public function product()
{
return $this->belongsTo('App\Product');
}
【问题讨论】:
-
我建议不要删除产品,因为您将失去这种关系。或者至少,不要进行硬删除。您可以使用soft deleting,以便它们仍然存在于数据库中,但除非您专门查找已删除的项目,否则它们会被隐藏。
-
@aynber 感谢您的回答。编辑产品怎么样?如何工作?
-
将产品直接链接到订单的问题是,如果产品被编辑,历史订单就会失控。我通常使用
product_name、product_price等将产品快照到订单上(以及一个单独的表order_products),这样编辑/删除就不会弄乱它。它仍然由id链接,但松散;它更喜欢快照值而不是实时值。 -
@TimLewis 如果我理解正确,我应该将价格、产品名称和其他名称移至 orders_products 表吗?
-
快照在这种情况下意味着在创建订单时复制产品信息并将其保存到单独的表 (
orders_products) 中。这假设订单可以有多个产品。但是这样,当编辑产品时,orders_products上的数据不会更新,因此您不会遇到问题。这有点宽泛,有点需要在设置初始项目时考虑到这一点,所以我可能无法为这个问题提供实际答案;只是我在开发电子商务系统时使用的指南。
标签: php database laravel laravel-5 eloquent