1
0

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 5 years have passed since last update.

collectionを使いましょう

Posted at

デリートインサートしたくない(一旦削除してまた紐付けると、sort_orderが変わってしまう)
Laravel の collection $this->model->related_artists->whereNotIn('id', $request->artist_id))が便利なので使えるものは使う


            // 関連アーティスト
            // 紐付けが解除されたアーティストがいれば、対象アーティストの紐付けも削除
            if ($UnassociatedArtists = $this->model->related_artists->whereNotIn('id', $request->artist_id)) ##こここ* {
                foreach ($UnassociatedArtists as $UnassociatedArtist) {
                    $UnassociatedArtist->related_artists()->detach($this->model->id);
                }
            }
            if (isset($request->artist_id) && count($request->artist_id) > 0 ) {
                $sortOrder = 1;
                foreach ($request->artist_id as $artistId) {
                    // 関連アーティストを配列に格納
                    $artistSelfSyncData[$artistId] = [
                        'artist_id' => $this->model->id,
                        'sort_order' => $sortOrder,
                    ];
                    $sortOrder++;

                    $artist = $this->find($artistId);
                    // 対象アーティストに編集中のアーティストが紐付いていなければ、対象アーティストの紐付けも追加
                    if ($artist->related_artists->where('id', $this->model->id)->count() == 0) {
                        // sort_orderの最大値 + 1
                        $targetArtistSortOrder = $artist->related_artists->max('pivot.sort_order') + 1;
                        $targetArtistSyncData[$this->model->id] = [
                            'artist_id' => $artistId,
                            'sort_order' => $targetArtistSortOrder,
                        ];
                        $artist->related_artists()->syncWithoutDetaching($targetArtistSyncData);
                    }
                }
                // 関連アーティストの保存(同期)
                $this->model->related_artists()->sync($artistSelfSyncData);
            } else {
                $this->model->related_artists()->detach();
            }
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?