繁体   English   中英

如何在 Laravel 中删除产品但不删除与该产品关联的订单?

[英]How to delete products but not orders associated with that product in Laravel?

我希望卖家能够删除/编辑他列出的产品。 但如果该产品已由客户订购,我希望订单保持不变且不会更改。 我怎样才能做到这一点?

现在当我更新/删除它会影响之前提交的订单。 这就是我现在删除产品的方式。

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

订单产品.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');
}

SoftDeletes特征添加到您的产品模型中。

要检索包括已删除产品在内的产品,请使用以下命令:


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OrderProduct extends Model
{
    protected $table = 'order_product';
    protected $fillable = ['order_id', 'seller_id','product_id', 'quantity','Subtotal','total'];


    public function product()
    {
        return $this->belongsTo('App\Product')->withTrashed();
    }

}

如果您不想显示已删除的产品,可以将->whereNull('p.deleted_at')到检索产品的函数中:

$products = DB::table('recommends AS r')
            ->leftJoin('products AS p', 'r.product_id', '=', 'p.id')
            ->join('products_photos AS pp', 'pp.product_id', '=', 'p.id')
            ->whereNull('p.deleted_at')
            ->select('p.id', 'p.pro_name', 'filename', 'p.pro_price', 'pro_info', DB::raw('COUNT(*) AS total'))
            ->groupBy('p.id', 'p.pro_name', 'filename', 'p.pro_price', 'pro_info')
            ->orderby('total', 'DESC')
            ->take(4);

它应该可以解决您的问题。

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM