【问题标题】:How to add a constraint to a table with Laravel's migrations?如何使用 Laravel 的迁移向表添加约束?
【发布时间】:2017-07-18 19:46:31
【问题描述】:

假设我有一个表periods,其中包含start_date 和end_date 列,我想添加一个约束start_date < end_date。

PostgreSQL 查询将是:

ALTER TABLE periods ADD CONSTRAINT check_dates CHECK ("start_date" < "end_date");

但我想将其作为 PHP 的迁移。我猜它看起来像这样:

Schema::table('periods', function (Blueprint $table) { $table->something(); });

...但即使使用 IntelliSense,我也猜不出要写什么而不是“something()”。

我没有使用最新版本的 Laravel,所以如果你添加你的代码从哪个版本工作以及你可以在旧版本中做什么,那就太好了。

【问题讨论】:

    标签: laravel laravel-migrations


    【解决方案1】:

    您可以运行如下所示的一些原始 SQL,因为 Blueprint 类仍然不支持约束。

    public function up()
    {
        DB::statement('ALTER TABLE periods ADD CONSTRAINT check_dates CHECK ("start_date" < "end_date")');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-01
      • 2021-08-30
      • 2016-11-08
      • 1970-01-01
      • 2019-03-24
      • 2017-03-27
      • 1970-01-01
      • 2020-09-21
      相关资源
      最近更新 更多