make:migration 的骚操作

看教程的时候发现,在执行 php aritsan make:migration add_extra_to_users_table 的时候并没有指定表名,但是生成的迁移文件确是指定表名 users 的。不明所以,这是什么操作?本想提问,算了,还是先翻翻源码吧,果不其然,被我找到了

首先找到了 writeMigration(),该方法作用是将生成的迁移文件写入磁盘。
Illuminate/Database/Console/Migrations/MigrateMakeCommand.php

.
.
/**
 * 将迁移文件写入磁盘。
 *
 * @param  string  $name
 * @param  string  $table
 * @param  bool    $create
 * @return string
 */
protected function writeMigration($name, $table, $create)
{
    $file = pathinfo($this->creator->create(
        $name, $this->getMigrationPath(), $table, $create
    ), PATHINFO_FILENAME);
    $this->line("<info>Created Migration:</info> {$file}");
}
.
.

该方法接收三个参数,其中第二个参数 $table 为表名,这就是我要找的为什么该条命令针对的是 users 表。找到该方法的调用处--也就是该文件的 handle() 方法:

.
.
/**
 * 执行命令.
 *
 * @return void
 */
public function handle()
{
    // 从命令输入中获取文件名
    $name = Str::snake(trim($this->input->getArgument('name')));
    // 从命令输入中获取 table 参数值
    $table = $this->input->getOption('table');
    // 从命令输入中获取 create 参数值
    $create = $this->input->getOption('create') ?: false;
    // 如果 table 值不存在,则把 create 赋值给 table
    if (! $table && is_string($create)) {
        $table = $create;
        $create = true;
    }
    if (! $table) {
        [$table, $create] = TableGuesser::guess($name);
    }
    $this->writeMigration($name, $table, $create);
    $this->composer->dumpAutoloads();
}
.
.

很显然,调用了 TableGuesser::guess($name),找到文件:
Illuminate/Database/Console/Migrations/TableGuesser.php

.
.
class TableGuesser
{
    const CREATE_PATTERNS = [
        '/^create_(\w+)_table$/',
        '/^create_(\w+)$/',
    ];
    const CHANGE_PATTERNS = [
        '/_(to|from|in)_(\w+)_table$/',
        '/_(to|from|in)_(\w+)$/',
    ];
    /**
     * 尝试猜测给定迁移的表名和"创建"状态
     *
     * @param  string  $migration
     * @return array
     */
    public static function guess($migration)
    {
        foreach (self::CREATE_PATTERNS as $pattern) {
            if (preg_match($pattern, $migration, $matches)) {
                return [$matches[1], $create = true];
            }
        }
        foreach (self::CHANGE_PATTERNS as $pattern) {
            if (preg_match($pattern, $migration, $matches)) {
                return [$matches[2], $create = false];
            }
        }
    }
}

哦吼,原来是匹配了命令输入的 add_extra_to_users_table
嗯,约定优于配置 真的可以省很多事啊

本作品采用《CC 协议》,转载必须注明作者和本文链接
:computer: & :coffee:
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

返回值为什么要声明一个$create

 foreach (self::CREATE_PATTERNS as $pattern) {
            if (preg_match($pattern, $migration, $matches)) {
                return [$matches[1], $create = true];
            }
        }
5年前 评论

@lovecn $create = true 是创建表, $crate = false 是更新表

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!