laravel - Eloquent 保存多对多关系而不重复

标签 laravel laravel-5 eloquent

我使用的是 Laravel 5.5,产品标签 之间存在多对多关系,数据透视表包含 product_idtag_id 作为仅有的两列。

我的模型如下:

class Product extends Model
{
    public function tags()
    {
        return $this->belongsToMany( 'App\Tag' );
    }
    // other code
}

class Tag extends Model
{
    public function product ()
    {
        return $this->belongsToMany( 'App\Product' );
    }

    protected $fillable = [ 'slug' ];
}

标签表包含 idslug 和时间戳列。我正在尝试将从逗号分隔字符串中的表单获取的标签分配给具有以下代码的产品:

$tags_r = explode( ',', $request->tags );

$tags = [];

foreach ( $tags_r as $tag ) {
    $tags[] = new Tag( [ 'slug' => strtolower( trim( $tag ) ) ] );
}

$p->tags()->saveMany( $tags );

我的问题是,当我尝试在 tags.slug 列上不受限制地保存标签时,我最终在几行上出现了重复的标签。当我将 slug 列设置为唯一以避免重复时,代码会抛出一个错误,提示约束。 如何做到这一点,以便如果标签存在,则通过使用数据透视表将其分配给产品,并且仅将其添加为 tags 表中的新行(如果尚未添加)存在吗?

最佳答案

您可以使用firstOrCreate()以避免将已有的标签添加到数据库中。

foreach ( $tags_r as $tag ) {
    $tags[] = Tag::firstOrCreate(['slug' => str_slug($tag)]);
}

$p->tags()->saveMany( $tags );

我还用过str_slug()而不是手动创建 slug。

关于laravel - Eloquent 保存多对多关系而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000163/

相关文章:

mysql - Laravel 无法连接到 Azure MySQL

php - 带参数调用 Controller

php - 在 eloquent 中的连接表字段上应用 order by

laravel - Route.php 类 Controller 中的 ReflectionException 不存在

MySQL : How to identify users I follow or follow me from other person's followers?

php - 在 Eloquent 模型事件中获取先前的属性值

php - Laravel 会记住 http 测试期间的原始响应

php - 如何在laravel中加载css和js文件

php - Laravel artisan 迁移失败

php - 一般错误 : 1 near ")": syntax error") in Laravel 5. 6.33