我在模型文章中使用软删除,但在模型注释中不使用软删除。我还使用模型文章中的段塞列定制了键。如果这篇文章被删除了,我还想显示评论。但是当文章被删除时,show方法总是返回404。
public function show(Article $article, Comment $comment)
{
if ($article->id != $comment->article_id)
throw new NotFoundHttpException('Record Not Found.');
return $this->success(['comment => $comment']);
}怎么解决这个问题?
发布于 2022-09-22 05:56:04
您的问题陈述并没有定义您应该问如何绑定软删除路由和模型的问题。
Laravel为此提供了->withTrashed()方法,因此它还可以在路由中绑定软删除模型。
web.php
user App/Http/Controller/ArticleController;
Route::get('article/{article}', [ArticleController::class, 'show'])->name('article.show')->withTrashed();,但是这个方法是在 Laravel 8.55中添加的,如果您有较早的版本,那么您可以在控制器中找到模型,而无需路由模型绑定。
ArticleController.php
public function show($article, App/Comment $comment)
{
$article = App/Article::withTrashed()->findOrFail($article);
if ($article->id != $comment->article_id) {
throw new NotFoundHttpException('Record Not Found.');
}
return $this->success(['comment => $comment']);
}或者您也可以将显式约束用于RouteServiceProvider中的特定模型。
public function boot()
{
parent::boot();
Route::bind('article', function ($id) {
return App\Article::withTrashed()->find($id) ?? abort(404);
});
}此外,还可以在显式绑定中使用onlyTrashed()方法,以防使用单独的路径处理被破坏的模型。
发布于 2022-09-22 04:38:16
如果您也希望删除记录,请使用withTrashed方法--您的代码应该如下所示:
Article::withTrashed()->find($id);希望它能帮助你和快乐的编码!
https://stackoverflow.com/questions/73809355
复制相似问题