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:
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 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年前 评论

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