laravel8で多対多の中間テーブルにて、外部キー以外のカラムの値を更新したい時はupdateExistingPivot()を使う
参考URL
https://www.wakuwakubank.com/posts/387-laravel-relation-3/
https://readouble.com/laravel/8.x/ja/eloquent-relationships.html
例えば、UserモデルとBookモデルで、予約の中間テーブルを作った時に優先順位もカラムに持たせたい!
user_id
book_id
priority
みたいな中間テーブルを作って、priorityを更新したい時は、updateExistingPivot()を使う
ユーザ(user_id=1)が予約している本(book_id=2)の優先順位(priority)を3にupdateする
| 1 2 3 | $user = User::find(1); $book_id = 2; $user->reserved_books()->updateExistingPivot($book_id, ['priority' => 3]); | 
中間テーブルの外部キー以外のカラムにアクセスするためには、リレーションの時にwithPivot()で明記する必要がある
app/Http/Models/User.php
| 1 2 3 4 5 6 7 | // このユーザが予約している本リスト public function reserved_books() {     return $this->belongsToMany(Book::class)     ->withPivot(['priority'])     ->orderBy('priority', 'asc'); } | 
pivot(中間テーブル)経由で、priorityカラムにアクセスできる
| 1 2 3 4 5 | $user = User::find(1); foreach ($user->reserved_books as $reserved_book) {     echo $reserved_book->pivot->priority;     echo $reserved_book->pivot->book_id; } |