laravel-5 - 如何使用迁移 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 迁移中定义这个,以便每个类别都应该有一个唯一的产品名称。?
解决方案
您可以使用表中的一组键创建自己的主键,如下所示:-
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');
}
这将确保每个名称都有一个唯一的产品/类别。
推荐阅读
- java - 如何通过 thymeleaf 访问 html 文件中的可选值?
- java - 执行 Android 应用程序时显示不相关的应用程序名称 - gradle 错误?
- swift - 如何解决由于 macOS 应用程序上的 CIFilter 导致的错误
- python - 如何使用 python selenium 单击带有文本 bb1 的元素
- c - 我正在尝试使用指针通过函数更改结构中的值,但是在函数中输入地址时出现错误
- angular - 为什么 red 和 IntelliJ 不支持 Angular 中的有效模型?
- javascript - 来自响应的值是未定义的 ReactJs
- python-3.x - 计算损失时的 Keras Nan 值
- angular - 如何使用角度的可观察对象在两个组件之间共享对象数组?
- python - 如何计算熊猫数据框中子组内项目的成对出现?