我有一个表'posts',其中包含一个外键'user_id,我如何在迁移时将该键添加到表中?

问题描述 投票:0回答:1

这是迁移

 Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->timestamps();

我已经尝试过使用此行

$table->bigInteger(‘user_id’)->unsigned()->nullable()->default(null);
$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);

我做了什么

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer(‘user_id’)->unsigned()->nullable()->default(null);
            $table->foreign(‘user_id’)->references(‘id’)->on(‘users’)-
            >onDelete(‘cascade’);

我得到什么ErrorExceptionenter

使用未定义常量'user_id'-假定为'user_id'(这将在以后的PHP版本中引发错误)

mysql migration database-migration laravel-7
1个回答
0
投票

@@幻影三个问题:

  1. 您为什么使用反引号而不是单引号?
  2. 为什么您应该只使用$table->id();来使用$table->integer('id');
  3. 您为什么应该将$table->timestamps();设为$table->timestamp('created');

此调整通过调整为单引号而不是反引号,正确使用$table->id();$table->timestamp('created');对我来说很好:

<?php

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

class Posts extends Migration
{
     public function up()
    {
        if(!Schema::hasTable('posts')) {
            Schema::connection('migrate')->create('testPosts', function (Blueprint $table) {
                $table->integer('id');
                $table->integer('user_id')->unsigned()->nullable()->default(null);
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->timestamp('created');
            });
        }
    }

    public function down()
    {
        if(Schema::hasTable('posts')) {
            Schema::connection('migrate')->dropIfExists('posts');
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.