简体   繁体   English

Laravel integer 值 DB 记录列的最大值限制

[英]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.如果可能的话,我将如何在我的数据库中创建一个具有最大限制的 integer 列。

Example:例子:

  • Let's call the column X让我们称列X
  • Let's say the max limit is "30"假设最大限制是“30”
  • if X is set to 12, then that is a valid value.如果 X 设置为 12,那么这是一个有效值。
  • if X is set to 31, then that is an invalid value.如果 X 设置为 31,那么这是一个无效值。

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您需要运行原始 sql 查询

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. SQL 限制数据库中的最小值和最大值,不知道 laravel 是否支持检查约束。 But you can create the table by hand.但是您可以手动创建表格。 - @DefinitelynotRafal - @DefinitelynotRafal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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