【问题标题】:Laravel - How to show details of a soft deleted modelLaravel - 如何显示软删除模型的详细信息
【发布时间】:2020-06-30 09:00:25
【问题描述】:

我在我的模型quotation 中使用软删除。删除quotation 会在数据库中保留带有deleted_at 字段的行。

我更新了我的索引方法以包含软删除模型:

    public function index()
    {
        $quotations = Quotation::withTrashed()->orderBy("id", "asc")->paginate(100);

        return view('quotations.index', compact('quotations'));
    }

但是我的 show 方法不起作用,我收到 404 Model Not Found 错误:

    public function show(Quotation $quotation)
    {
        $quotation = Quotation::withTrashed()->find($quotation->id);
        return view('quotations.show', compact('quotation', 'activities'));
    }

【问题讨论】:

  • 404 Model Not Found error 你的意思是类Quotation 没有找到吗?如果是这样,那么 use App\Quotation 在控制器顶部。

标签: laravel


【解决方案1】:

你正在使用route-model-binding,它会自动从没有withTrashed()的模型Quotation中找到$id并注入变量$quotation。所以在数据库中找不到匹配的模型实例$quotation,会自动生成一个404 HTTP响应。:

$quotation = Quotation::find($id);

解决方案一:

所以你可以尝试直接使用$id

    public function show($id)
    {
        $quotation = Quotation::withTrashed()->find($id);
        return view('quotations.show', compact('quotation', 'activities'));
    }

然后将您的路线从{quotation} 更改为{id}

解决方案 2:

自定义解析逻辑:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Route::bind('quotation', function ($value) {
        return App\Quotation::withTrashed()->where('id', $value)->first() ?? abort(404);
    });
}

【讨论】:

    【解决方案2】:

    我认为您将通过以下方式获得 id:

    public function show() {
        $quotation = Quotation::withTrashed()->where('id',2)->get();
        return $quotation;
    }
    

    【讨论】:

      【解决方案3】:

      如果您只想将其应用于单个模型,您可以这样做。覆盖模型中的 resolveRouteBinding 方法(适用于 Laravel 8):

      /**
       * Retrieve the model for a bound value.
       *
       * @param  mixed  $value
       * @param  string|null  $field
       * @return \Illuminate\Database\Eloquent\Model|null
       */
      public function resolveRouteBinding($value, $field = null)
      {
          return $this->withTrashed()->where($field ?? $this->getRouteKeyName(), $value)->first();
      }
      

      相关:Can I change the resolution logic for Route-Model-Binding to always lowercase the string key?.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-05
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多