Octobercms onSave更新其他型号

时间:2018-01-31 18:00:14

标签: model relation octobercms

我需要在保存贷款时更新模型关系中图书的status字段,但它无效。

我的代码

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();

}
}

错误:

`"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`

1 个答案:

答案 0 :(得分:0)

我试过这个codeits working fine你可以尝试这个。

它位于我的model which model I am saving内,所以当saving is done我是updating related demo model's 状态字段时,似乎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();
}

更新

您似乎已更新了答案而且它的关系 is Many to Many 所以现在我有no proper solution一次一次更新多条记录因为集合update方法未生成proper query structure因此会导致collection update出错。

但是我有can fire multiple queries的其他解决方案,但现在它seems working solution for your issue

您的关系是belongsToMany我们需要不同的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();

    });     
}
  

确保您的Book模型没有afterSave逻辑,如果,则确保不更新您的父模型< / strong>在您的情况下Lending,因为会调用无限循环

请尝试这个并告诉我们。