简体   繁体   中英

Max value limit for Laravel integer value DB record column

How would I, if possible, create an integer column in my database with a max limit.

Example:

  • Let's call the column X
  • Let's say the max limit is "30"
  • if X is set to 12, then that is a valid value.
  • if X is set to 31, then that is an invalid value.

I would like to do this in the database layer and not in my application layer.

So what would I put in my database migration file?

Example migration file:

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Column value limitation can be done via check constraint

Blueprint does not support it.

You need to run raw sql query

public function up()
{
    // table creation
    DB::statement('
        ALTER TABLE users 
        ADD CONSTRAINT users_x_check CHECK (x > 0 AND x <= 30)
    ');
}

SQL Limit min and max value in database , no clue if laravel supports check constraints. But you can create the table by hand. - @DefinitelynotRafal

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