Try associate
$details = UserDetail->find(1);
$details->firstname = 'Firstname';
$adress = new Address();
$details->addresses()->associate($address);
$address->name = 'Address';
$address->city = 'City';
$dettaglio->push();
Firtzberg said:
Try associate
$details = UserDetail->find(1); $details->firstname = 'Firstname'; $adress = new Address(); $details->addresses()->associate($address); $address->name = 'Address'; $address->city = 'City'; $dettaglio->push();
Ty, I tried it but don't work.
With the code below seems to work but i don't know if it's correct. I need suggestion for a better solution. :)
$detail = UserDetail::find(1);
$detail->firstname = 'Firstname Test';
$detail->surname = 'Surname Test';
$testInput = [
['address_id' => 1, 'address_name' => 'Street Test 1'],
['address_id' => 2, 'address_name' => 'Street Test 2'],
];
foreach ($testInput as $row) {
$address = Address::find($row['address_id']);
$address->name = $row['address_name'];
$detail->addresses()->save($address);
}
$detail->push();
You're right. Associate sets only the foreign key column.
I your approach every address is saved separately. SaveMany is better.
$detail->addressed()->saveMany($addresses);
Your question is about updating, not inserting. I think if the model is retreived from the database it contains "old values", and saveMany() should have a similar effect like save() on that models. That means it should recognize that there are old values, and make an update, instead of insert.
Call saveMany() on an array of Addresses where some are from the database and with changed column values and others new. Swap them. Checkout the query with
dd(DB::getQueryLog());
Post the result here, I'm interested.
I used saveMany() for insert some addresses but didn't work on update. This method want an argument with an array model:
Example from Laravel docs:
$comments = array(
new Comment(array('message' => 'A new comment.')),
new Comment(array('message' => 'Another comment.')),
new Comment(array('message' => 'The latest comment.'))
);
I don't know how to make an array model for updating and not for inserting datas...
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community