简体   繁体   中英

Update one-to-many relation in Laravel: Array to string conversion error

I'm trying to update multiple rows but I face an array to string conversion error. Donation to Donation Items is a one-to-many relation and up to 5 types of items may be updated. I've already tried using solution from Update multiple rows of database in Laravel and used the saveMany() method but I'm still not able to update the given rows.

Here's what I tried:

    $n = 0;
    $donationItems = DonationItems::where('donation_id', $donationId)->get();
    foreach ($donationItems as $item) {

        $itemName = $r->get('item-name');
        $itemQuantity = $r->get('item-quantity');

        $item->name = $itemName;
        $item->quantity = $itemQuantity;
        $item->donation_id = $donation->id;

        $donation->donationItems()->save($item);

        $n += 1;
    }

Change your line

$donation->donationItems()->save($item);

For

$item->save();

Since you already set the donation_id on your $item , you don't need to save them through the relation

You can just use update() method which will create just one query instead of N queries:

DonationItems::where('donation_id', $donationId)
    ->update([
        $item->name = $r->item-name;
        $item->quantity = $r->item-quantity;
        $item->donation_id = $donation->id;
    ]);

This will work as long as you're properly using $fillable array in the model:

protected $fillable = ['name', 'quantity', 'donation_id'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM