【问题标题】:How to create composite key in Laravel?如何在 Laravel 中创建复合键?
【发布时间】:2020-08-25 06:47:00
【问题描述】:

我尝试了很多方法,但没有任何效果。我需要向我的表 daily_deals_products 添加一个复合键。使用 laravel 和 mysql 开发的。

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDailyDealsProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('daily__deals__products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('product_id');
            $table->timestamps();

      
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('daily__deals__products');
    }
}

【问题讨论】:

    标签: php mysql laravel composite-key


    【解决方案1】:
    Schema::create("daily__deals__products", function($table) {
        $table->increments('id');
        $table->integer('product_id');
        $table->string('name');
    });
    
    DB::unprepared('ALTER TABLE `daily__deals__products` DROP PRIMARY KEY, ADD PRIMARY KEY (  `id` ,  `product_id` )');
    

    【讨论】:

    • 这样对吗,$table->unique(['id','product_id']);?
    • 它是复合键,所以如果我没记错的话,你的场景中不需要外键约束
    • 谢谢@Naveed Ali。不使用使用数据库;它完美地工作。如果使用它,就会出错。抱歉,我无法为您的答案投票,因为我的声望不到 15。还有一个问题,如果我需要添加另一列,我该怎么做?@Naveed Ali
    • 如果这个问题对你有帮助,那么你可以接受这个答案
    • 如果刷新数据会丢失。不是吗?
    【解决方案2】:

    试试这个:

    $table->primary(['id','product_id']);
    
    
    public function up()
    {
        Schema::create('daily__deals__products', function (Blueprint $table) {
            $table->primary(['id', 'product_id']);
            $table->unsignedInteger('id');
            $table->foreignId('product_id')->nullable()->constrained()->onDelete('cascade');
    
        }
    

    【讨论】:

    • 我在使用时遇到了这个错误。 SQLSTATE [42000]:语法错误或访问冲突:1068 定义了多个主键(SQL:alter table daily_deals_products 添加主键 daily_deals_products_id_product_id_primary(id, product_id))@Abdulmajeed
    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多