如何在不创建数据到联结点的情况下将数据创建到联结表中的多对多关系 [英] How to create data into junction table many to many relationship without create data into the junction point to

查看:59
本文介绍了如何在不创建数据到联结点的情况下将数据创建到联结表中的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它同时将表插入标签和标签中,我想要的只是插入到标签(结)表中.导致在将其插入到标签之前,有代码首先检查标签是否将插入到已存在的标签表中,如果存在,则仅获取ID.为了简化我的问题.我只是不包括用于检查标签是否存在的代码.

It inserts both table inside tags and tagables, what i want is just to insert into tagables ( junction ) table. Cause before it insert into tagables, theres code to check first if tag will insert into tags table already exist or not, if exist just grab the id. To make it simple to my problem. i just don't include code to check if tags is exist or not.

帖子模型

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

推荐答案

我认为最简单的方法是使用雄辩的方法"firstOrCreate"创建标签,然后在已有新标签或现有标签的情况下创建标签您可以将此标签添加到新帖子.该代码可能看起来像这样:

I think the simplest way do this to start by creating the tag with the eloquent method 'firstOrCreate', and then when you already have a new tag or existing tag you can add this tag to a new Post. The code may look like something like this:

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',
    
        ]);

这篇关于如何在不创建数据到联结点的情况下将数据创建到联结表中的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆