从Laravel控制器中的不同标签删除2行

因此,我有2个名为'主题'和'帖子'的表。从Laravel控制器中的不同标签删除2行

主题是线程和主题的主要内容的答复。

所以,我想如果用户删除它的话题,那么它的下面的回复/帖子也应该删除。

这是我删除形式:

{!! Form::open(['action' => ['[email protected]', $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:

You may also specify the desired action for the "on delete" and "on update" properties of the constraint

定义在posts表迁移外键约束:

$table->foreign('topic_id') 

->references('id')

->on('topics')

->onDelete('cascade');

重新创建表和与主题相关的所有帖子将在主题删除被自动删除。在Docs

Topic::destroy($id); 

Post::where('topic_id', $id)->delete();

return redirect('/')->with('Success', 'Post Removed');

回答:

更多信息,您应该使用在主题,帖子关系和答复模型,展现例如每次回复属于一个职位。

回答:

https://laravel.com/docs/5.5/migrations#foreign-key-constraints

以上是 从Laravel控制器中的不同标签删除2行 的全部内容, 来源链接: utcz.com/qa/265456.html

回到顶部