繁体   English   中英

如何在 Laravel 中使用一列作为多外键?

[英]How can I use one column as multi foreign key in Laravel?

我想将一列用作两个不同表的外键。 我怎样才能在 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');
}

错误

PDOException::("SQLSTATE[HY000]: General error: 1826 Duplicate foreign key constraint name 'order_details_order_id_foreign'")

laravel 给出了相同的名称,因为所有列的名称都相同,只需重命名第二个外键

    $table->foreign('order_id','order_details_order_id_foreign_cart')
    ->references('id')
    ->on('cart_controls')
    ->onDelete('cascade');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM