【问题标题】:Delete parent table data when deleted all related child rows form child table in laravel在laravel中从子表中删除所有相关子行时删除父表数据
【发布时间】:2018-09-10 11:48:52
【问题描述】:

这是我的父表:-

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

这是子表:-

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

当我使用外键删除与父移动数据相关的所有子数据时,我还想删除父表中的移动数据。

【问题讨论】:

  • 你在使用 laravel 查询生成器
  • @Krishanu 是的..
  • 那我建议你做点数之类的事情。子表中具有 parent_id 的行数,例如,1。如果为 0,则从父表中删除该行。如果你给我几分钟,我可以自己尝试一个代码
  • @Krishanu 兄弟,但我认为 MySQL 没有提供任何通过使用子表数据删除父表行来删除的功能。
  • 确实如此。加入是一个很好的方法

标签: php laravel-5.5


【解决方案1】:

在您的删除语句后添加此代码

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

确保您为此使用查询生成器

如果您使用的是 eloquent,而不是 DB,则添加 ..

use DB;

课前。

希望这能解决您的问题!

【讨论】:

    【解决方案2】:

    在您的删除语句后添加此代码

    $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,而不是 DB,则添加 ..

    use DB;
    

    课前。

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多