使用“artisan migrate”时如何更改时间戳列名?

时间:2013-07-18 23:12:48

标签: php laravel laravel-4

我正在努力改变由

生成的时间戳列名称
php artisan migrate

命令。

我已经做了以下更改。当我使用eloquent查询构建器时,它可以正确生成列名,但是当我使用上面的命令时,它仍然会生成" created_at"," updated_at"和" deleted_at"。谁能帮我吗?非常感谢。

/* vendor\framework\src\Illuminate\Database\Eloquent\Model.php */

/**
 * The name of the "created at" column.
 *
 * @var string
 */
const CREATED_AT = 'datetime_created';

/**
 * The name of the "updated at" column.
 *
 * @var string
 */
const UPDATED_AT = 'datetime_updated';

/**
 * The name of the "deleted at" column.
 *
 * @var string
 */
const DELETED_AT = 'datetime_deleted';

/* vendor\framework\src\Illuminate\Database\Schema\Blueprint.php */

/**
 * Indicate that the timestamp columns should be dropped.
 *
 * @return void
 */
public function dropTimestamps()
{
    $this->dropColumn('datetime_created', 'datetime_updated');
}

/**
 * Add a "deleted at" timestamp for the table.
 *
 * @return void
 */
public function softDeletes()
{
    $this->timestamp('datetime_deleted')->nullable();
}
/**
 * Add creation and update timestamps to the table.
 *
 * @return void
 */
public function timestamps()
{
    $this->timestamp('datetime_created');

    $this->timestamp('datetime_updated');
}
/**
 * Add a "deleted at" timestamp for the table.
 *
 * @return void
 */
public function softDeletes()
{
    $this->timestamp('datetime_deleted')->nullable();
}

P.S。我知道修改"核心"并不是一个好主意。如果有人能告诉我扩展这些课程的最佳方法,我会非常感激。

1 个答案:

答案 0 :(得分:19)

不要编辑vendor文件夹下的代码。首先,它通常(默认情况下)不随您的存储库一起提供,因此如果您或其他任何人想要在另一台计算机上工作,您将丢失更改。 第二次,在您执行composer update时会被覆盖。


好吧,那就是说,让我们开始处理这个“修改核心”的恐怖。对于Illuminate\Database\Eloquent\Model.php,只需创建一个基本模型,您将从中扩展所有后续模型,并覆盖其中的常量:

应用/模型/ BaseModel.php

abstract class BaseModel extends Eloquent {

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'datetime_created';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'datetime_updated';

    /**
     * The name of the "deleted at" column.
     *
     * @var string
     */
    const DELETED_AT = 'datetime_deleted';

}

然后,对于Illuminate\Database\Schema\Blueprint案例......嗯,它变得血腥:

  1. 扩展..\Schema\Blueprint,覆盖您提到的方法。
  2. 扩展..\Schema\Builder,覆盖createBlueprint方法以使用新的Blueprint课程。
    • 同时延长..\Schema\MySqlBuilder以扩展您的新Builder课程。
  3. 扩展..\Connection,覆盖getSchemaBuilder方法以使用新的Builder课程。
    • 同时延伸..\MySqlConnection..\PostgresConnection..\SqlServerConnection..\SQLiteConnection以扩展您的新Connection课程。
    • 注意: ..\MySqlConnection还需要将getSchemaBuilder方法扩展为使用新的MySqlBuilder类。
  4. 扩展..\ConnectionFactory,覆盖createConnection方法以使用扩展的Connection类。
  5. 创建ServiceProvider以将新的ConnectionFactory类注册为新的db.factory组件,并将其添加到app/config/app.php文件的providers下。< / LI>

    所以,经过半个小时的挖掘,通过Laravel的源代码来解决这个问题,我得出的结论是,可能更容易在迁移中执行以下操作:

    $table->timestamp(BaseModel::CREATED_AT);
    $table->timestamp(BaseModel::UPDATED_AT);