Dmitry Skibitsky
Dmitry Skibitsky

Reputation: 104

Laravel. setRelation(s) - adds only the last relationship

php: 7.3.4
Laravel Framework 5.7.28

Hi, everybody. Help add data for all relations. Now for some reason it turns out that only the last relation is added. setRelations works similarly.

code

public static function firstOrCreateModel() {
        $cart = Cart::firstOrCreate(self::getWhereQuery());

        if ($cart->delivery === 1) {
            $cart->setRelation('np_area', $cart->with('npArea')->first());
            $cart->setRelation('np_city', $cart->with('npCity')->first());
            $cart->setRelation('np_warehouse', $cart->with('npWarehouse')->first());
            dump($cart->toArray());
        }

        return $cart;
    }

Result. GIF screen recording

Upvotes: 3

Views: 1663

Answers (1)

Ahmed Aboud
Ahmed Aboud

Reputation: 1322

setRelation() does not save to the DB setRelation its just for testing you better use sync() if its many-to-many or attach() if its one-to-many

Upvotes: 1

Related Questions