如何在 Laravel 中创建组合键?

How to create composite key in Laravel?

我试了很多方法都没有用。我需要向我的 table 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');
    }
}

试试这个:

$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');

    }
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` )');