php - 一般错误 : 1215 Cannot add foreign key constraint

标签 php mysql laravel

我正在尝试从 products 表获取 price 值并将其设置为 sold 表。你能告诉我为什么会收到此错误吗? product_iduser_id 工作正常。但是当我需要在 sold 表中创建外国 price 时,出现错误

已售

    Schema::create('sold', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');    
        $table->integer('product_id')->unsigned();  
        $table->foreign('product_id')->references('id')->on('products');
        $table->integer('price')->unsigned();
        $table->foreign('price')->references('price')->on('products');   
        $table->integer('bid_price')->unsigned();
        $table->foreign('bid_price')->references('bid_price')->on('products');     
        $table->timestamps();
    });

产品

    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('slug');
        $table->string('title');
        $table->text('body');
        $table->integer('price');
        $table->integer('bid_price');
        $table->string('address');
        $table->string('condition');
        $table->integer('quantity');
        $table->string('img_1');
        $table->string('img_2');
        $table->string('img_3');
        $table->string('img_4');
        $table->integer('views');
        $table->timestamps();
    });

错误消息:

General error: 1215 Cannot add foreign key constraint (SQL
  : alter table `sold` add constraint sold_price_foreign foreign key (`price`
  ) references `products` (`price`))

编辑

`LATEST FOREIGN KEY ERROR
------------------------
2016-03-01 12:40:08 31a0 Error in foreign key constraint of table auction/#sql-2564_ef:
foreign key (`price`) references `products` (`price`):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.`

最佳答案

Cannot find an index in the referenced table

您的产品表需要在您尝试引用的列上有一个索引。我想说这必须是唯一的,否则 MySQL 无法确定它引用的是哪一行。

关于php - 一般错误 : 1215 Cannot add foreign key constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35720332/

相关文章:

php - mysql 按天过滤

PHP:使用外部连接文件时关闭mysql连接

javascript - 如何使用 Ajax 和 JQuery 调用带参数的 php 函数

php - 表单生成器中的关联数组字段 - Symfony3

php - MySQL连接查询超过1个id

Mysql客户端内存不足

php - 根据列表长度将来自 mysql 的结果列表拆分为单独的列表

php - Eloquent 模型更新更多的行,它应该 laravel php

php - 我可以从新的 Laravel 5 安装中删除哪些文件夹和文件

laravel - 如何调整bootstrap轮播高度?