针对一个外键验证重复数据



>我有两个表,两个表都像这样合并到第三个表中

**sub_category**
Id 
Name
**category**
ID
Name
**sub_cat**
ID
sub_id
cat_id
**category**                  **Sub_Category**
ID   Name                     ID        Name
1    One_Cat                   1        one_sub
2    two_Cat                   2        two_sub
3    three_Cat                 3        three_sub
**Cat_SubCat**
ID      Cat_id      sub_catId
1         1         1
2         1         2
3         1         3
4         1         1
5         2         1
6         2         2
7         2         2

您是否看到在cat_id1下有sub_CatId的副本, 我想要的是验证,在类别 1 下,类别 2 不应该有重复的子类别,类别 2 下不应该有重复的子类别

如果您在类别和子类别表中的名称具有唯一性,则意味着 ID 将始终是唯一的。因此,无需验证关系是否已存在,您可以简单地使用、sync()syncWithoutDetaching()这将确保类别和子类别之间始终有一个连接,并且没有重复。否则,您将使用产生重复项的attach()

查看文档了解更多信息

https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships

迁移应如下所示:

Schema::create('sub_cat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('sub_id');
$table->unsignedBigInteger('cat_id');
$table->unique(['sub_id', 'cat_id']);
});

unique指数确保sub_idcat_id是唯一的。

然后,每当您想添加子类别时,请使用syncsyncWithoutDetaching.

但是为什么要设计这样的表格,你应该只在category表上使用parent_id

Schema::create('category', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('category');
$table->unsignedBigInteger('parent_id')->nullable;
$table->foreign('parent_id')->references('id')->on('category');
});

然后,Category模型应如下所示:

class Category extends Model
{
public function parentCategory()
{
return $this->belongsTo(self::class, 'parent_id');
}
public function subCategories()
{
return $this->hasMany(slef::class, 'parent_id');
}
}

最新更新