删除 parent table 数据时删除所有相关的 child 行形成 child table in laravel

Delete parent table data when deleted all related child rows form child table in laravel

这是我的 parent table:-

id | name    | created_at
 1 | mobile  |  NULL
 2 | Laptop  |  Null 

这是 Child table:-

id | name  |parent_id| amount | created_at
 1 | Nokia |    1    | 2500   | NULL
 2 |Samsung|    1    | 3500   | Null
 3 |Sony   |    1    | 4000   | Null 

当我通过外键删除 parent 移动数据相关的所有 child 数据时,我还想删除 parent table 中的移动数据.

在删除语句后添加此代码

$child = DB::table('child')->where('parent_id',$id)->get();
if($child->count() == 0){
    $parent = DB::table('parent')->where('id', $id)->delete();;
}

确保为此使用查询生成器

如果您使用的是 eloquent,而不是数据库,则添加 ..

use DB;

在 class.

之前

希望这能解决您的问题!

在删除语句后添加此代码

$parent = DB::table('parent')->find($id);
$child = DB::table('child')->where('parent_id',$id)->get();
if($child->count() == 0){
  $parent = DB::table('parent')->where('id', $id)->delete();
}else{
  $child = DB::table('child')->where('parent_id',$id)->delete();
}
$parent = DB::table('parent')->where('id', $id)->delete();

如果您使用的是 eloquent,而不是数据库,则添加 ..

use DB;

在 class.

之前