【问题标题】:How to create data into junction table many to many relationship without create data into the junction point to如何在不将数据创建到连接点的情况下将数据创建到连接表中的多对多关系中
【发布时间】:2021-04-10 17:07:33
【问题描述】:

它在标签和可标记中插入表,我想要的只是插入到可标记(连接)表中。因为在它插入到 tagables 之前,有代码首先检查 tag 是否会插入到 tags 表中是否已经存在,如果存在就获取 id。为了让我的问题变得简单。我只是不包含检查标签是否存在的代码。

发布模型

public function tags(){ return $this->morphToMany( Tag::class, 'tagable', 'tagables', null, 'tag_id ); }

后控制器

// tags table theres a row id 1 with name greeting
$post = Post::create( ['body' => 'Hello World'] );
$post->tags()->create( ['tag_id' => 1] );

表格

// posts table
$table->mediumIncrements('post_id');
$table->string('body');

// tags table
$table->mediumIncrements('tag_id');
$table->string('tag_name');

//tagables table
$table->unsignedMediumInteger('tag_id');
$table->unsignedMediumInteger('tagable_id');
$table->string('tagable_type');

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我认为最简单的方法是首先使用 eloquent 方法“firstOrCreate”创建标签,然后当您已经有了新标签或现有标签时,您可以将此标签添加到新帖子中。代码可能如下所示:

    class Tag extends Model
       {
        
    
        protected $guarded = [];
    
        public function posts()
        {
            return $this->morphedByMany(Post::class, 'taggable');
        }
       }
    
       
    
       
    
      $tag = Tag::firstOrCreate(
                ['tag_name' => 'traveling'],
            );
        
            $post = $tag->posts()->create([
                'body' => 'My new interesting post',
        
            ]);
    

    【讨论】:

    • 我使用相同的参数来显式 morphedByMany 但它返回未知列。 Unknown column 'tag_tag_id' in 'field list' (SQL: insert into media_tags` (media_type, tag_id, tag_tag_id) 值 (3, 6, 1))` 错误 return $this->morphedByMany(Post::class,'tagable', 'tagables', null, 'tag_id');
    • 这种方式的问题,如何多次输入标签名?如果 1 没问题,可以说有 13 个标签。 a,b,c,d,e,f,g,h 等等如果逻辑先创建标签然后创建帖子。它将创建多个帖子。
    • $tag1 = Tag::firstOrCreate( ['name' => 'tag1'], ); $tag2 = Tag::firstOrCreate( ['name' => 'tag2'], ); $post = Post::create([ 'name' => 'tag name1', ]); $insertData = [ ['tag_id' => $tag1->id, 'taggable_id' => $post->id, 'taggable_type' => Post::class], ['tag_id' => $tag2->id, 'taggable_id' => $post->id, 'taggable_type' => Post::class], ];可标记::insert($insertData);
    • 我也有这个想法,用junction做模型。但它会以典型的方式变得笨拙。使用结作为模型。我最好使用 DB 类来明确模型是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2018-06-18
    • 2019-07-06
    • 1970-01-01
    • 2021-10-18
    • 2021-05-03
    • 1970-01-01
    相关资源
    最近更新 更多