I want to use one column as a foreign key for two different tables. How can I do that on Laravel?
Schema::create('order_details', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('order_id');
$table->unsignedBigInteger('product_id');
$table->float('price');
$table->string('stock_keeping_unity');
$table->integer('quantity');
$table->foreign('order_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('order_id')
->references('id')
->on('cart_controls')
->onDelete('cascade');
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
}
Error
PDOException::("SQLSTATE[HY000]: General error: 1826 Duplicate foreign key constraint name 'order_details_order_id_foreign'")
laravel gives teh same name because you have both times the same names for all columns, simple rename the second foreign key
$table->foreign('order_id','order_details_order_id_foreign_cart')
->references('id')
->on('cart_controls')
->onDelete('cascade');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.