【问题标题】:I have a table 'posts' which contains a foreign key 'user_id, how can i add that key to table on migration?我有一个表“posts”,其中包含一个外键“user_id”,如何在迁移时将该键添加到表中?
【发布时间】:2020-08-24 08:37:09
【问题描述】:

这是迁移

 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’);

我得到了什么 错误异常进入

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

【问题讨论】:

  • 请重新检查使用的报价。也许你使用了错误的字符。它们应该是 " 或 ' (就像您使用 'posts' 一样),但不是 `(反引号),也不是像您所拥有的特殊:$table->integer(‘user_id’)

标签: mysql migration database-migration laravel-7


【解决方案1】:

@Mirage 三问:

  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');
        }
    }
}

【讨论】:

  • 为什么使用反引号而不是单引号?回答:我是从源头那里得到的,但你是对的。回答第二个问题:它来自 laravel 用户迁移模板,或者那是不同的情况!第三个问题:好点,,,我正在学习,它是我的第一个项目(但它看起来像它的 $table->timestamp(); 它自动创建(created_at updated_at)
  • 它创建了表但我仍然得到这个 SQLSTATE[HY000]: 一般错误: 1215 无法添加外键约束 (SQL: alter table posts add constraint posts_user_id_foreign foreign key (user_id ) 在删除级联时引用users (id)
  • 当您首先尝试创建部分外键的表时,可能会出现问题。我会参考此文档来删除外键约束,然后将表全部删除,然后尝试重新运行迁移。让我知道当你这样做时会发生什么。
  • 那个键不知何故起作用了,我试图以同样的方式添加另一个外键,但它抛出了错误......,我失去了理智
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 2015-10-29
  • 2019-10-19
  • 1970-01-01
  • 2011-01-31
  • 2020-06-27
  • 2015-11-17
相关资源
最近更新 更多