Laravel 5 - 使用数据向现有表添加列和外键

时间:2017-09-18 13:38:49

标签: laravel-5 laravel-5.4

我在Laravel非常新!但我正在努力。这是我可以使用一些帮助;

我有一张帖子表。我有一个用户表。但是我忘了在post表中添加一个链接到用户ID的外键。

创建用户表迁移:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

创建帖子表格迁移:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

我创建了新的迁移文件:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AlterTablePostsAddForeignUser extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::table('posts', function (Blueprint $table) {
          // I HAVE NO IDEA WHAT TO DO NEXT
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

我不知道如何填写"公共功能up()"方法在这里!如果有人可以帮忙!非常感谢!

2 个答案:

答案 0 :(得分:0)

查看文档here

您需要在修改列之前安装doctraine/dbal,确保将doctrine / dbal依赖项添加到composer.json文件中。 Doctrine DBAL库用于确定列的当前状态并创建对列进行指定调整所需的SQL查询,您应该尝试我在this上发现的帖子

Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id')->unsigned()->change();

    $table->foreign('user_id')->references('id')->on('users');
}); 
用于更改列

的结构的

change()方法

在此之后运行工匠命令

php artisan migrate

如果这对您不起作用,请在此处发表评论! :)

答案 1 :(得分:0)

我尝试过,这对我有用。

Schema::table('posts', function (Blueprint $table) {
      $table->integer('user_id')->nullable()->unsigned();
      $table->foreign('user_id')->references('id')->on('users');
 });

此处添加外键时,默认情况下它将具有Null值。此``null引用''可能会导致问题。使用nullable()外键可以避免该问题。