如何使用迁移laravel为该特定类别产品名称设置唯一功能应该是唯一的?

问题描述 投票:0回答:1

有两张桌子。在类别下有一个产品名称。因此,此产品名称必须是唯一的。像cat1有pro1,pro2 cat2有pro1,pro3

表1(迁移):

<?php

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

class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('catefory', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
    }

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

Tbl2(迁移)

   public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->foreign('category_id')->references('id')->on('category');
    
            $table->timestamps();
        });
    }

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

对于每个类别,应该有唯一的产品名称。如何在laravel迁移中定义它,以便每个类别都应该有一个唯一的产品名称。

laravel-5
1个回答
0
投票

您可以使用表格中的一组键创建自己的主键,如下所示: -

Tbl2(迁移)

   public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->primary(['name', 'category_id']);
            $table->string('name');
            $table->foreign('category_id')->references('id')->on('category');

            $table->timestamps();
        });
    }

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

这将确保每个名称都具有唯一的产品/类别。

© www.soinside.com 2019 - 2024. All rights reserved.