我正在尝试从 products
表获取 price
值并将其设置为 sold
表。你能告诉我为什么会收到此错误吗? product_id
和 user_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/