【问题标题】:Foreign key cross-databases error in laravel 4laravel 4中的外键跨数据库错误
【发布时间】:2014-03-30 20:49:50
【问题描述】:

我使用外键“user_id”迁移到另一个数据库中的表“用户”: 当我输入(php artisan migrate)时,这会产生错误。

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'user_id
' doesn't exist in table (SQL: alter table `safetyreports` add constraint s
afetyreports_user_id_foreign foreign key (`user_id`) references `users` (`i
d`) on delete cascade)

现在 laravel 制作了除了 'user_id' 列之外的表格。 laravel 为什么不做专栏?

这是我的迁移代码:

Schema::create('safetyreports', function(Blueprint $table) {
            $table->increments('id');
            $table->string('afdeling');
            $table->string('contractor');
            $table->string('directe chef');
            $table->string('ploeg');
            $table->string('team');
            $table->string('plant_afd');
            $table->string('datum');
            $table->string('plaats');
            $table->string('tijd');
            $table->string('omschrijving');
            $table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');
            $table->timestamps();
        });

This is a the important part of my Users model code: 

protected $connection = 'mysql2';
protected $table = 'users';


I have tested my Users model. It works. I perform (cross-database) user authentication with this model. 

【问题讨论】:

    标签: database laravel-4 foreign-keys eloquent


    【解决方案1】:

    发生这种情况是因为您尝试为尚不存在的表的列创建外键。查看 --pretend 输出。在创建地址和点表之前创建外键。将密钥的创建移到另一个迁移中,它将为湖增添魅力

    【讨论】:

      【解决方案2】:

      在声明外键之前,必须先声明字段。

      您需要先声明

      Schema::create('safetyreports', function(Blueprint $table) { 
              ...
              $table->integer('user_id')->unsigned();
              ...
      });
      

      注意unsigned 部分对此无法预测。

      一旦您声明了该字段,您就可以随意声明它的关系。

      希望对你有帮助...=D

      【讨论】:

      • 现在几乎可以使用了。只得到错误:General error: 1215 Cannot add foreign key constraint (SQL : alter table safetyreports add constraint safetyreports_user_id_foreign foreign key (user_id) references users (id) on delete cascade)
      • 删除过去“手动”创建的整个表并再次运行它。 =D 应该可以!
      • 如果它对您有用,请考虑接受并点赞它,这样它可以帮助其他人! =D
      猜你喜欢
      • 2014-06-09
      • 2015-03-02
      • 2018-11-08
      • 2014-10-22
      • 1970-01-01
      • 2015-09-25
      • 2014-03-01
      • 2015-03-17
      • 1970-01-01
      相关资源
      最近更新 更多