从Laravel Controller中的不同标签中删除2行

问题描述 投票:0回答:3

所以,我有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.

这里做错了什么?

php laravel laravel-5
3个回答
1
投票

使用级联删除。

来自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


0
投票

更多信息在Docs

Topic::destroy($id);
Post::where('topic_id', $id)->delete();
return redirect('/')->with('Success', 'Post Removed');

0
投票

您应该在主题,帖子和回复模型中使用关系,以显示例如每个回复属于帖子。

© www.soinside.com 2019 - 2024. All rights reserved.