如果父表中的行被删除,如何自动从子表中删除行

时间:2018-09-28 09:58:18

标签: mysql laravel database-design eloquent

我有两个表(客户和预订)

customer_table:

<?php
require('connection.php');
require('fetch.php');
if(isset($_GET['customer_mobile'])) {
    $delete_id = mysql_real_escape_string($_GET['customer_mobile']);
    $sql = mysql_query("DELETE FROM customer_deatil WHERE id = '".$delete_id."'");
    if($sql) {
        echo "<br/><br/><span>deleted successfully...!!</span>";
    } else {
        echo "ERROR";
    }
}
?>

bookings_table:

|       id       |
|      name      |
|   created_at   |
|   updated_at   |

如何创建一个迁移文件,该文件将在删除客户后删除所有与该客户有关的预订?

1 个答案:

答案 0 :(得分:2)

只需将外键onDelete设置为级联

Schema::create('bookings_table', function (Blueprint $table) {
    $table->increments('id');
    $table->string('product');
    $table->unsignedInteger('customer_id');
    $table->timestamps();

    $table->foreign('customer_id')
        ->references('id')
        ->on('customer_table')
        ->onDelete('cascade')
        ->onUpdate('cascade');
});