代码之家  ›  专栏  ›  技术社区  ›  Shadid

如何使laravel蓝图变形方法在指定列后添加列

  •  10
  • Shadid  · 技术社区  · 7 年前

    Schema::table('books', function(Blueprint $table)
            {
                $table->string('reference')->after('access');
            });
    

    这将在访问列之后创建我的引用列。但是如果我想使用变形,我会怎么做呢。我在考虑这么做

    Schema::table('books', function(Blueprint $table)
            {
    
                $table->morphs('reference')->after('access');
            });
    

    然而,当我尝试运行迁移时,这会给我带来一个迁移错误。这是因为变形没有 after 方法我使用的是laravel 5.1。我不确定访问后如何获得参考列。任何帮助或建议都会很好。非常感谢。

    1 回复  |  直到 7 年前
        1
  •  24
  •   stihl    7 年前

    $table->morphs()只是一个快捷方式。这是其背后的功能(Laravel 5.5):

    /**
     * Add the proper columns for a polymorphic table.
     *
     * @param  string  $name
     * @param  string|null  $indexName
     * @return void
     */
    public function morphs($name, $indexName = null)
    {
        $this->unsignedInteger("{$name}_id");
    
        $this->string("{$name}_type");
    
        $this->index(["{$name}_id", "{$name}_type"], $indexName);
    }
    

    Schema::table('books', function (Blueprint $table) {
        $table->unsignedInteger("reference_id")->after('access');
        $table->string("reference_type")->after('reference_id');
        $table->index(["reference_id", "reference_type"]);
    });