Laravel 5.4将带有外键的列添加到现有表错误中

时间:2017-06-02 00:09:35

标签: php mysql laravel-5.4

我尝试创建以下迁移文件来更新我的用户表:

<?php

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

    class AddSedeIdToUsersTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::table('users', function (Blueprint $table) {
                $table->integer('sede_id')->unsigned();
                $table->foreign('sede_id')->references('id')->on('sedes');
            });
        }

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

这是我的sedes迁移文件,我在表中播放了2个测试行

<?php

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

    class CreateSedesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('sedes', function (Blueprint $table)
            {
                $table->increments('id');
                $table->string('name')->nullable();
            });
        }

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

我的user.php模型

<?php

  namespace App;

  use App\Cuota;
  use App\ticketsIncidente;
  use App\ticketsMessage;
  use App\Sancion;
  use App\Reserva;
  use App\Espacio;
  use App\Sede;
  use Illuminate\Notifications\Notifiable;
  use Illuminate\Foundation\Auth\User as Authenticatable;

  class User extends Authenticatable
  {
      use Notifiable;

      /**
       * The attributes that are mass assignable.
       *
       * @var array
       */
      protected $fillable = [
          'name', 'email', 'password', 'role', 'facebook_id'
      ];

      /**
       * The attributes that should be hidden for arrays.
       *
       * @var array
       */
      protected $hidden = [
          'password', 'remember_token',
      ];


      public function user(){
          $this->hasOne('App\Sede');
          $this->hasMany('App\Cuota');
          $this->hasMany('App\Reserva');
          $this->hasMany('App\Sancion');
          $this->hasMany('App\ticketIncidente');
          $this->hasMany('App\ticketMessage');
          return;
      }    
  }

Sede.php类

<?php

  namespace App;

  use Illuminate\Database\Eloquent\Model;
  use App\User;

 class Sede extends Model
 {
     protected $fillable = ['name'];

     public function sede() {
         $this->belongsTo('App\User');
         return;
     }
 }

当我运行php artisan migrate时,它返回

  [Illuminate\Database\QueryException]                                         
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update   
  a child row: a foreign key constraint fails (`clubgaston`.`#sql-446_b3`, CO  
  NSTRAINT `users_sede_id_foreign` FOREIGN KEY (`sede_id`) REFERENCES `sedes`  
   (`id`)) (SQL: alter table `users` add constraint `users_sede_id_foreign` f  
  oreign key (`sede_id`) references `sedes` (`id`))                            



  [PDOException]                                                               
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update   
  a child row: a foreign key constraint fails (`clubgaston`.`#sql-446_b3`, CO  
  NSTRAINT `users_sede_id_foreign` FOREIGN KEY (`sede_id`) REFERENCES `sedes`  
   (`id`))                                                                     

提前致谢

2 个答案:

答案 0 :(得分:0)

无论错误alter table是否运行,sede_id是在users表中创建的,但是没有FOREIGN KEY引用;所以我运行了另一次迁移,但没有再次定义该列,只分配了外来的,它起作用了。

  public function up()
        {
            Schema::table('users', function (Blueprint $table) {
                $table->foreign('sede_id')->references('id')->on('sedes');
            });
        }

https://laravel.com/docs/5.4/migrations#foreign-key-constraints

答案 1 :(得分:-1)

那么,您是在尝试创建一对一或一对多关系?在Eloquent中,没有必要在迁移中引用ID的外键。创建Eloquent关系时,您只需要在users表中包含sede_id字段。因此,在您的AddSedeIdToUsersTable课程中,您的迁移将如下所示:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('sede_id');
    });
}

Eloquent将对其余部分进行排序,允许您利用现有的关系机制。 (请注意,如果您希望关系反向运行,则需要以相同的方式将user_id添加到sedes表。有关它的更多信息,请查看关于以下主题的Laravel文档:< / p>

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many