2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravel 多対多 タグ付け

Last updated at Posted at 2020-07-07

新しいの書いた
https://qiita.com/ma7ma7pipipi/items/a5ea71071fbaf9311cfe

参考
https://qiita.com/Ioan/items/bac58de02b826ae8e9e9

Profile テーブル
Tag テーブル

をそれぞれ 多対多 で結びつけたい。
profile の綴りを間違えないように気をつけて。

Profile.php

    public function tag(){
        return $this->belongsToMany('App\Tag', 'profile_tag', 'profile_id', 'tag_id');
    }


Tag.php

    public function profile(){
        return $this->belongsToMany('App\Profile', 'profile_tag', 'tag_id', 'profile_id');
    }

データ読み出し


        //タグをすべて読みだし、タグがいくつのプロフィールを持っているか取得
        $hoge = Tag::withCount('profile')
            ->orderBy('profile_count', 'desc')
            ->get();


//        タグとともにすべてのデータを取得
        $res = Profile::query()//単数形 User
            ->with('tag')
            ->get();

これでOK。
中間テーブルを複数作れば
User と Profile にTagテーブルのタグをつけれるようになる。

User.php

    public function tag(){
        return $this->belongsToMany('App\Tag', 'user_tag', 'user_id', 'tag_id');
    }


Tag.php

public function user(){
    return $this->belongsToMany('App\User', 'user_tag', 'tag_id', 'user_id');
}

タグ付けしたい

ProfileTag.phpを作成し、指定した記事を保存したあとに
タグは別途で保存する。

タグがすでにあれば、タグのIDを取得。
タグがなければタグを新規作成し、IDを取得。

また、保存する際は古いタグをすべて削除して再度新規保存する。

ProfileTag.php

class ProfileTag extends Model
{
    protected $table = 'profile_tag';//使うテーブル名を指定
    protected $guarded = ['hoge2'];
    use InsertOnDuplicateKey;
}

HogeContorller.php

<?php

    $profile_id = 22163702;
    
    $tags = [
        'ウェブショップ',
        'りんご',
        '小麦'
    ];
    
    $tag_ids = [];
    
    foreach ($tags as $v) {
    
        $tag = Tag::query()//単数形 User
        ->where('name',$v)
            ->first();//最初の
    
    
        if($tag){
    
    
            //あればタグのIDを取得
            $tag_ids[] = $tag['id'];
    
        } else {
    
            //なければ新規保存
            $model = new Tag;
            $model->name = trim($v);
            $model->save();
            $tag_ids[] = $model->id;
    
    
        }
    
    }
    
    
    $now =  Carbon::now();
    
    
    $data = [];
    foreach ($tag_ids as $v) {
    
        $data[] = [
            'id' => null,
            'profile_id' => $profile_id,
            'tag_id' => $v,
            'created_at' => $now,
            'updated_at' => $now
        ];
    
    }
    
    $data = array_values($data);
    
    
    ProfileTag::query()
        ->where('profile_id',$profile_id)
        ->delete();//削除
    
    ProfileTag::insertOnDuplicateKey($data);


2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?