【问题标题】:Which column type for storing the year field in a table with rows of yearly data哪种列类型用于将年份字段存储在具有年度数据行的表中
【发布时间】:2015-08-24 03:59:24
【问题描述】:

我的 Laravel 网络应用使用 schema builder 来实现数据库可移植性,因此 MySQL-specific YEAR column type 不可用。

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

【问题讨论】:

  • int 怎么样?或者,char(4) 也可以。
  • 难道不能在模式构建器中使用原始语句吗?

标签: mysql database laravel database-design


【解决方案1】:

你可以这样做吗:

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

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

}

【讨论】:

  • 这不是一个可移植的解决方案。
  • 为了加深我的理解,你能告诉我你所说的便携是什么意思吗?你的意思是这样你就可以在数据库之间切换,所以它不是特定于 mySql 的吗?
【解决方案2】:

我认为这应该可行:

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;
}

【讨论】:

  • 这不是一个可移植的解决方案。
【解决方案3】:

存储年份值的最佳便携式列类型是什么?

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

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

【讨论】:

    【解决方案4】:

    在 Laravel 5.8 中,你可以这样做:

    $table->year('birth_year');
    

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 2010-10-11
      • 2015-06-12
      • 2017-03-13
      相关资源
      最近更新 更多