vendredi 27 mai 2016

How to insert value to one to many relationship without save owning entity in Eloquent?

Let's say I have the following class:

class A 
{
   public function collections()
   {
       return $this->hasMany(B:class);
   }
}

What I'm trying to achieve is the ability to play with objects in memory without actually saving them in database first, for example:

public class A 
{
   public function addSomething()
   {
      $this->collections->add(new B());
      $this->collections->add(new B());
   }
}

$a = new A();
$a->addSomething();
$a->push();

But so far, my attempts were failed. When I called push(), records for B will be created without the correct id for A. In other words, no relationship are created. If I save $a by adding $this->save() before calling addSomething(), it will work as expected. However I feel it is weird since addSomething() should be just inserting value to the collection without saving anything.

What is the correct way to add value to collection without saving the owning entity first?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire