Preventing Laravel adding multiple records to a pivot table

后端 未结 5 1318
刺人心
刺人心 2020-12-22 18:54

I have a many to many relationship set up and working, to add an item to the cart I use:

$cart->items()->attach($item);

Which adds an

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-22 19:08

    There are some great answers posted already. I wanted to throw this one out here as well though.

    The answers from @AlexandreButynski and @Barryvdh are more readable than my suggestion, what this answer adds is some efficiency.

    It retrieves only the entries for the current combination (actually only the id) and it than attaches it if it does not exist. The sync method (even without detaching) retrieves all currently attached ids. For smaller sets with little iterations this will hardly be a difference, ... you get my point.

    Anyway, it is definitely not as readable, but it does the trick.

    if (is_null($book->authors()->find($author->getKey(), [$author->getQualifiedKeyName()])))
        $book->authors()->attach($author);
    

提交回复
热议问题