Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Try associate

$details = UserDetail->find(1);
$details->firstname = 'Firstname';

$adress = new Address();
$details->addresses()->associate($address);
$address->name = 'Address';
$address->city = 'City';

$dettaglio->push();
Last updated 2 years ago.
0

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();
Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

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...

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

wanted80 wanted80 Joined 22 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.