简体   繁体   中英

How to add a constraint to a table with Laravel's migrations?

Let's say I have a table periods with columns start_date and end_date and I want to add a constraint start_date < end_date .

The PostgreSQL query would be:

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

But I want to do it as a migration with PHP. I guess it will look something like this:

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

...but even with IntelliSense I couldn't guess what to write instead of "something()".

I'm not using the newest version of Laravel so it would be nice if you add from which version your code works and what can you do in older versions.

You can run some raw SQL like below as constraints are still not supported by the Blueprint class.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM