I am struggling to use laravel push()
function
My Code is here:
$company = new Company(array('name' => 'Company 1'));
$company->persons[] = new Person(array('name' => 'Company 1 Person 1', 'mobile' => 12345));
$company->persons[] = new Person(array('name' => 'Company 1 Person 2', 'mobile' => 112233));
$company->push();
When it gets stored:
Company gets stored well, but for company persons, it stores company_id
to 0
Larave Documentations says:
Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the push method:
$user->push();
what is wrong?
It's not Doctrine ;)
push
could do it, BUT it wouldn't be nice and easy (below you can find out how)
And here's what you can do instead (nice and easy way):
// still you need already existing Company, so save it first
$company = new Company(array('name' => 'Company 1'));
$company->save();
$company->persons()->createMany(array(
array('name' => 'Company 1 Person 1', 'mobile' => 12345),
array('name' => 'Company 1 Person 2', 'mobile' => 12345)
));
This will save new Person
models and associate them with the Company
push
would do the job, but only if you do it with already existing parent AND you first associate child models:
$company = Company::first(); // or any existing
$person = new Person(array('name' => 'Company 1 Person 1', 'mobile' => 12345));
$person->company()->associate($company);
$anotherPerson = new Person(array('name' => 'Company 1 Person 2', 'mobile' => 12345));
$anotherPerson->company()->associate($company);
$company->persons[] = $person;
$company->persons[] = $anotherPerson
$company->push();
Obviously this is more work and it's definitely not the way I would suggest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With