【问题标题】:foreign key error when migrate table in laravel 5.0在 laravel 5.0 中迁移表时出现外键错误
【发布时间】:2016-04-02 00:11:25
【问题描述】:

当我尝试在我的迁移文件中创建外键时,当我运行迁移命令时出现错误。在订单表中,我将 userID 作为外键,所以出现此错误

http://i.stack.imgur.com/1voZh.png

【问题讨论】:

  • 您能发布ordersusers 迁移文件吗?包括它的文件名。
  • @Tezla 是的,我将我的迁移文件发布在gist.github.com/24singhekta/998aab6fd372a3aa35f5
  • 当你创建外键时,你应该像这样分配你引用的表:$table->integer('product_id')->unsigned(); $table->foreign('product_id')->refrences('id')->on('products'); ——

标签: sql laravel laravel-5 foreign-keys laravel-migrations


【解决方案1】:

您需要对外键使用完全相同的类型。在users 你有:

$table->increments('id');

所以它是无符号整数,所以在 order 中而不是:

$table->integer('userID');

(signed int) 你需要使用:

$table->integer('userID')->unsigned();

(unsigned int) 使其工作。

【讨论】:

    【解决方案2】:

    或者,您可以按照以下步骤解决您的问题。

    在您的用户模型中编写此代码以关联订单。

    public function orders(){
        return $this->hasMany('App\Order');
    }
    

    您的“订单”表迁移将是这样的。

    Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');
        $table->text('extra_detail');
        $table->integer('user_id');
    });
    

    在您的订单模型中编写此代码以关联用户。

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

    您的“用户”表迁移将是这样的。

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
    });
    

    【讨论】:

    • 这不会解决她的参考问题。我想。
    • 当你创建外键时,你应该像这样分配你引用的表:$table->integer('product_id')->unsigned(); $table->foreign('product_id')->refrences('id')->on('products');
    猜你喜欢
    • 2018-05-03
    • 2014-04-03
    • 2019-01-31
    • 2014-09-27
    • 2021-02-21
    • 2019-02-09
    • 2018-09-22
    • 2016-07-06
    • 2015-08-14
    相关资源
    最近更新 更多