Laravel。 setRelation(s)-仅添加最后一个关系

时间:2019-04-22 19:19:36

标签: php laravel eloquent

php:7.3.4
Laravel Framework 5.7.28

大家好。帮助添加所有关系的数据。 现在,由于某种原因,事实证明仅添加了最后一个关系。 setRelations的工作方式与此类似。

代码

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

1 个答案:

答案 0 :(得分:1)

setRelation()不会保存到数据库KT-30986只是为了测试,如果它是多对多的,最好使用sync();如果是一对多,最好使用attach()