哪种列类型用于将年份字段存储在 table 中,其中包含年度数据行

Which column type for storing the year field in a table with rows of yearly data

我的 Laravel 网络应用程序使用 schema builder for database portability, so the MySQL-specific YEAR column type 不可用。

我希望能够按年份(包括 BETWEEN)对 select 行数据进行排序。存储年份值的最佳便携式列类型是什么?

你能做这样的事情吗:

public function up()
{
    Schema::create('mytable', function(Blueprint $table)
    {
        $table->increments('id');
        // columns
        $table->timestamps();
    });

    DB::statement('ALTER mytable ADD year YEAR' );

}

我认为这应该可行:

Schema::table('tablea_name', function(Blueprint $table)
{
    DB::statement('ALTER TABLE table_name ADD year YEAR(4);');
});

如果 Laravel 在即将推出的版本中提供任何方式来访问此方法(在 /vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php 中),则便携式解决方案将是:

/**
 * Add a new column to the blueprint.
 *
 * @param  string  $type
 * @param  string  $name
 * @param  array   $parameters
 * @return \Illuminate\Support\Fluent
 */
protected function addColumn($type, $name, array $parameters = array())
{
    $attributes = array_merge(compact('type', 'name'), $parameters);

    $this->columns[] = $column = new Fluent($attributes);

    return $column;
}

What's the best portable column type for storing year values?

smallint 是表示年的不错选择,它是 ANSI SQL,因此适用于大多数数据库。它将持续到 32767 年。

一些数据库支持 create domain,这基本上允许您创建自己的类型。您可以为其他数据库创建一个 year 域。不过,我更喜欢 smallint for year 的简单性。

从 Laravel 5.8 开始,您可以这样做:

$table->year('birth_year');