Ad

Octobercms OnSave Update Other Model

- 1 answer

I need to update the status field of the book in model relation when a loan is saved, but it is not working.

My code

class Lending extends Model
{

/**
 * @var string The database table used by the model.
 */
public $table = 'ribsousa_library_lendings';

/*
 * Relations
 */
public $belongsToMany = [
    'books' => [
        'Ribsousa\Library\Models\Book',
        'table' =>  'ribsousa_library_lendings_books',
        'order'      => 'title desc'
    ]
];

public function afterSave()
{

    $this->book->status = 1;
    $this->book->save();

}
}

The Error:

`"Indirect modification of overloaded property Ribsousa\Library\Models\Lending::$book has no effect" on line 95 of C:\wamp64\www\iepm.dev\plugins\ribsousa\library\models\Lending.php`
Ad

Answer

I have try this code and its working fine can you try this one.

it's inside my model which model I am saving , so when saving is done I am updating related demo model'sstatus field and seems its working.

public $belongsTo = [
    'demo' => 'HardikSatasiya\DemoTest\Models\Demo',
    'user' => 'RainLab\User\Models\User'
];

/**
 * @var string The database table used by the model.
 */
public $table = 'hardiksatasiya_demotest_relation';

public function afterSave() {
    $this->demo->status = 1;
    $this->demo->save();
}

Update

It seems you have updated answer and It's Relation is Many to Many so for now I have no proper solution for updating multiple record at once, because collection update method is not generating proper query structure so it throws error for collection update.

But I have other solution which can fire multiple queries but for now it seems working solution for your issue.

your Relation is belongsToMany sow we need different approch.

public function afterSave() {
    $this->books()->each(function($book) {
        $book->update(['status' => 1]);
        // if you get mass assign error -use this
        // $book->status = 1;
        // $book->save();

    });     
}

Make sure your Book model don't have any afterSave logic and if it has then just make sure it don't update your parent model in your case Lending, as it will call infinite loop.

please try this and let us know.

Ad
source: stackoverflow.com
Ad