首页 > 解决方案 > 如何使用迁移 laravel 为该特定类别产品名称设置唯一功能应该是唯一的?

问题描述

有两张桌子。在一个类别下有一个产品名称。那么,这个产品名称必须是唯一的。?就像 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

解决方案


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


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

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


推荐阅读