[英]Deleting 2 rows from different label in Laravel Controller
So, i have 2 tables named 'topics' and 'posts'. 因此,我有2个表分别称为“主题”和“帖子”。
Topics is for the main content of the thread and posts for its reply. 主题是主题的主要内容,主题是主题的回复。
So, i want to if the user delete its topic, then its following reply/post should also be deleted. 因此,我想如果用户删除其主题,则其以下答复/帖子也应删除。
Here is my delete form: 这是我的删除表格:
{!! 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() !!}
and here is controller: 这是控制器:
$topic = Topic::find($id);
$post = Post::where('topic_id', $id)->get();
$topic->delete();
$post->delete();
return redirect('/')->with('Success', 'Post Removed');
But it is giving error: 但这给了错误:
BadMethodCallException
Method delete does not exist.
What is did wrong here?? 这是怎么了?
Use cascade deleting. 使用级联删除。
You may also specify the desired action for the "on delete" and "on update" properties of the constraint
您还可以为约束的“删除时”和“更新时”属性指定所需的操作
Define a foreign key constraint in posts
table migration: 在
posts
表迁移中定义外键约束:
$table->foreign('topic_id')
->references('id')
->on('topics')
->onDelete('cascade');
Recreate the table and all posts related to the topic will be automatically deleted on topic deletion. 重新创建表,与主题相关的所有帖子将在删除主题时自动删除。
https://laravel.com/docs/5.5/migrations#foreign-key-constraints https://laravel.com/docs/5.5/migrations#foreign-key-constraints
您应该在主题,帖子和回复模型中使用关系,以显示例如每个回复都属于一个帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.