首页 > 解决方案 > 如何在laravel中显示软删除的项目?

问题描述

我有一个属于许多产品的订单(数据透视表)和一张属于订单的发票!我使用软删除在我的订单中显示产品(它有效),现在我想在我的发票中显示那些被丢弃的物品!我怎样才能做到这一点?在订单模型中,我有这个:

public function products()
{
    return $this->belongsToMany('App\Product','order_product','ord_id','prod_id')->withPivot('prod_quantity','discount')->withTimestamps();
}

在发票控制器中我有这个:

public function show($id)
{
    $invoice = Invoice::with('order.products')->find($id);
    
    return response()->json([
        'error' => false,
        'invoice' => $invoice,
    ],200);
}

标签: laravellazy-loading

解决方案


利用withTrashed()

public function show($id)
{
    $invoice = Invoice::withTrashed()
          ->with('order.products')
          -->find($id);
    
    return response()->json([
        'error' => false,
        'invoice' => $invoice,
    ],200);
}

编辑

确保您的模型使用软删除特征。

https://laravel.com/docs/7.x/eloquent#soft-deleting


推荐阅读