我使用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'中删除一行时,表的这些数据不会被删除。任何的想法?感谢
答案 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');
public function down()
{
Schema::table('phong', function (Blueprint $table) {
$table->dropForeign('khu');
});
}