使用 Laravel 的 foreignIdFor 方法并创建复合唯一键

Using Laravel's foreignIdFor method and create a composite unique key

按照下面的语法,我可以轻松地根据字段 namebakery_id 创建一个复合唯一键:

Schema::create('product_categories', function (Blueprint $table) {
    $table->id();
    $table->foreignId('bakery_id')->constrained();
    $table->string('name', 30);
    $table->boolean('enabled')->default(true);
    $table->timestamps();

    $table->unique(['bakery_id', 'name']);
});

当我使用“foreignIdFor()”方法而不是“foreignId()”时,有没有办法以编程方式确定列的名称?

Schema::create('product_categories', function (Blueprint $table) {
    $table->id();
    $table->foreignIdFor(Bakery::class)->constrained();
    $table->string('name', 30);
    $table->boolean('enabled')->default(true);
    $table->timestamps();

    $table->unique(['???', 'name']);
});

我没听懂你的问题,但也许这会有所帮助

Schema::create('product_categories', function (Blueprint $table) {
   $table->id();
   // $table->foreignIdFor(Bakery::class)->constrained();
   $table->unsignedInteger('bakery_id')->nullable();
   $table->foreign('bakery_id')->references('id')->on('bake')->onDelete('cascade');
   $table->string('name', 30);
   $table->boolean('enabled')->default(true);
   $table->timestamps();

   $table->unique(['bakery_id', 'name']);
});

只需要捕获列定义并使用它:

Schema::create('product_categories', function (Blueprint $table) {
    $table->id();
    $colDef = $table->foreignIdFor(Bakery::class)->constrained();
    $table->string('name', 30);
    $table->boolean('enabled')->default(true);
    $table->timestamps();

    $table->unique([$colDef->name, 'name']);
});