所以,我有2个名为'topics'和'posts'的表。
主题是线程的主要内容和回复的帖子。
因此,我想如果用户删除其主题,则还应删除其后续回复/帖子。
这是我的删除表格:
{!! Form::open(['action' => ['TopicController@destroy', $topic->id], 'method' => 'POST', 'class' => 'pull-right']) !!}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
{!! Form::close() !!}
这是控制器:
$topic = Topic::find($id);
$post = Post::where('topic_id', $id)->get();
$topic->delete();
$post->delete();
return redirect('/')->with('Success', 'Post Removed');
但它给出了错误:
BadMethodCallException
Method delete does not exist.
这里做错了什么?
使用级联删除。
来自the docs:
您还可以为约束的“on delete”和“on update”属性指定所需的操作
在posts
表迁移中定义外键约束:
$table->foreign('topic_id')
->references('id')
->on('topics')
->onDelete('cascade');
重新创建表格,与主题相关的所有帖子将在删除主题时自动删除。
https://laravel.com/docs/5.5/migrations#foreign-key-constraints
更多信息在Docs
Topic::destroy($id);
Post::where('topic_id', $id)->delete();
return redirect('/')->with('Success', 'Post Removed');
您应该在主题,帖子和回复模型中使用关系,以显示例如每个回复属于帖子。