【问题标题】:Laravel- Set default in foreign keyLaravel-在外键中设置默认值
【发布时间】:2018-08-30 05:37:02
【问题描述】:

我使用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' 中删除一行时,该表的数据不会被删除。任何想法?谢谢

【问题讨论】:

标签: php sql laravel


【解决方案1】:

外键约束

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');
    });
}

Read the full docs

【讨论】:

  • 我用“级联”没问题。但它不适用于“设置默认”约束
  • 我明白了。当我在您的回答下方添加下拉列时。感谢您的支持:)
猜你喜欢
  • 2015-01-10
  • 2019-10-29
  • 2012-03-07
  • 2015-01-25
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
相关资源
最近更新 更多