【问题标题】:Soft delete in laravel and model bindinglaravel 和模型绑定中的软删除
【发布时间】:2017-01-04 12:10:47
【问题描述】:

我已经为 Laravel 5.2 应用了 documentation 中提到的软删除。我有一个 [get] 路线和另一个 [delete] 路线:

Route::get('profile/{id}/delete', 'uses' => 'ProfileController@delete');
Route::delete('profile/{id}', 'uses' => 'ProfileController@destroy');

控制器方法如下:

public function delete($id)
{
    $profile = Profile::with('contract.division')->withTrashed()->where('id', $id)->first();

    return view('pages.profiles.delete', compact('profile'));
}

public function destroy($id)
{
    $profile = Profile::withTrashed()->find($id);

    $profile->delete();

    return redirect('employees/list');
}

当我尝试使用非垃圾 id 时,使用此代码我得到了内容。如果我尝试使用已删除的 ID,则会收到以下错误:

没有模型 [App\Profile] 的查询结果。 (查看:\xyz\xyz\xyz\resources\views\pages\profiles\delete.blade.php)

  1. 尽管错误意味着当我在删除方法中 dd($profile) 时没有查询结果,但我得到了具有关系的完整模型。那么出了什么问题呢?!

  2. 当类型提示配置文件函数 delete(Profile $id) 我得到了 404 的垃圾模型,我应该如何修复路由以使配置文件准备好 withTrashed() ?

【问题讨论】:

  • 您是否将use SoftDeletes; 特征添加到您的Profile.php 模型中?它可能正在寻找。也尝试改用$profile->destroy($id);
  • 是的,我添加了特征,我的问题是当用户获得删除或恢复确认的形式时第一条路线的错误。假设当前模型已被删除并且我想恢复它,所以我需要获取该模型信息以进行恢复。

标签: laravel soft-delete


【解决方案1】:

类型提示垃圾模型会给你 404,因为当你为垃圾模型雄辩时,你必须指定 withTrashed()

如果您只想在系统中进行垃圾处理,可以尝试

if(!$profile->trashed()){
    $profile->delete();
}

【讨论】:

  • 404 是在方法中键入提示模型时出现问题,但是收到已丢弃模型时的错误怎么办?如何解决无查询结果问题?
【解决方案2】:

我发现最好的方法是在绑定名称上使用后缀或前缀。

例子:

$controllerPath = 'UsersController';
$routeName = 'users';
$routeBindNameTrashed = "user_trashed";
Route::bind($routeBindNameTrashed, function($userId) use () {
  return App\User::onlyTrashed()->findOrFail($userId);
});

Route::put("$routeName/{{$routeBindNameTrashed}}/restore", "{$controllerPath}@restore")->name("{$routeName}.restore");
Route::delete("$routeName/{{$routeBindNameTrashed}}/force", "{$controllerPath}@forceDelete")->name("{$routeName}.force-delete");

我的真实例子

完整示例:https://stackoverflow.com/a/62143846/9813428

【讨论】:

    猜你喜欢
    • 2013-10-27
    • 2023-03-20
    • 2017-07-29
    • 2018-06-19
    • 2021-10-02
    • 2016-03-30
    • 1970-01-01
    • 2018-04-15
    • 2014-09-28
    相关资源
    最近更新 更多