我需要在保存贷款时更新模型关系中图书的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`
答案 0 :(得分:0)
我试过这个code
和its 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
,因为会调用无限循环。
请尝试这个并告诉我们。