Laravel-在外键中设置默认值

时间:2018-03-21 07:34:12

标签: php sql laravel

我使用SET DEFAULT来限制外键:

public function up()
    {
        Schema::create('phong', function (Blueprint $table) {
            $table->engine='InnoDB';
            $table->bigIncrements('p_id');
            $table->string('p_ma',50);
            $table->string('p_ten',50);
            $table->unsignedTinyInteger('p_soNguoi')->default('0');
            $table->text('p_ghiChu',200)->nullable();
            $table->unique(['p_ma','p_ten']);
            $table->timestamp('p_taoMoi')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('p_capNhat')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->unsignedTinyInteger('p_trangThai')->default('2');
            $table->unsignedTinyInteger('lp_ma');
            $table->unsignedTinyInteger('k_ma');
            $table->foreign('lp_ma')->references('lp_ma')->on('loaiphong')->onDelete('SET DEFAULT')->onUpdate('SET DEFAULT');
            $table->foreign('k_ma')->references('k_ma')->on('khu')->onDelete('SET DEFAULT')->onUpdate('SET DEFAULT');
        });
    }

但是这不起作用,这个错误是:外键约束在   正确形成。  当我想从表'khu'或'loaiphong'中删除一行时,表的这些数据不会被删除。任何的想法?感谢

1 个答案:

答案 0 :(得分:0)

外键约束

  

Laravel还支持创建外键约束,这些约束用于强制数据库级别的引用完整性。例如,让我们在posts表上定义一个user_id列,该列引用users表上的id列:

Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users');
});
  

您还可以为约束的“on delete”和“on update”属性指定所需的操作:

$table->foreign('user_id')
  ->references('id')->on('users')
  ->onDelete('cascade');

Drop Column

public function down()
{
    Schema::table('phong', function (Blueprint $table) {
        $table->dropForeign('khu');
    });
}

Read the full docs