php - laravel 5 insert relationship between two tables -


user hasmany profiles profile belongs user.

following works:

    $u = user::firstornew(['email' => $s['email']]);     $u->name   = $s['name'];     $u->avatar = $s['avatar'];     $u->save();      $p = new userprofile;     $p->provider     = $s['provider'];     $p->provider_uid = $s['provider_uid'];      if ($u->profiles()->save($p)) {      } 

but don't it, there better more streamlined way? why can't save in 1 atomic insert?

you trying save data 2 different table, that's why can't using single insert.

the way - first save parent object, associate child object , save - how done.

you have @ push() method of eloquent's models, works in similar fashion save() calls save() on related models. using method allows replace code:

$a = new a; $a->save();  $b = new b; $b->a()->associate($a); $b->save(); 

with

$a = new a;  $b = new b; $b->a()->associate($a);  $a->push(); 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

qt - Passing a QObject to an Script function with QJSEngine? -

c# - Web API response xml language -