我正在尝试删除它们之间的两个相关表中的数据。因此,当我删除 websites 表中的一行时,我还想删除 keywords 表中与外键相关的行
网站
编号 |站点名称
1 |例子
关键字
编号 |网站编号 | kwName
1 | 1
所以当我删除一个网站时,具有相同id(website_id作为外键)的行不会被删除。
我的删除代码是:
Controller
public function destroy($id)
{
$projects = Website::findOrFail($id);
$projects->delete();
return redirect()->route('projects.index')->with('alert-success','Data Has been Deleted!');
}
Blade
@foreach($projectss as $projects)
<tr>
<td>{{$no++}}</td>
<td>{{$projects->siteName}}</td>
<td>{{$projects->siteUrl}}</td>
<td>
<form class="" action="{{route('projects.destroy',$projects->id)}}" method="post" enctype="multipart/form-data">
<input type="hidden" name="_method" value="delete">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<a href="{{route('projects.show',$projects->id)}}" class="btn btn-success">View</a>
<a href="{{route('projects.edit',$projects->id)}}" class="btn btn-primary">Edit</a>
<input type="submit" class="btn btn-danger" onclick="return confirm('Are you sure to delete this data');" name="name" value="delete">
</form>
</td>
</tr>
@endforeach
模型关键字.php
public function website() {
return $this->belongsTo('App\Website');
}
模型 Website.php
public function keywords() {
return $this->hasMany('App\Keyword');
}
最佳答案
实现此目的的最佳方法是在定义外键约束时使用onDelete('cascade')
:
$table->foreign('website_id')->references('id')->on('websites')->onDelete('cascade');
因此,当您删除一个网站时,与该网站相关的所有关键字都会自动删除。
https://laravel.com/docs/5.4/migrations#foreign-key-constraints
关于mysql - Laravel 同时删除两个相关表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41966007/