【问题标题】:Octobercms onSave update other modelOctobercms onSave 更新其他模型
【发布时间】:2018-07-10 22:39:50
【问题描述】:

我需要在保存贷款时更新模型关系中图书的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`

【问题讨论】:

标签: model relation octobercms


【解决方案1】:

我试过这个codeits working fine 你能试试这个吗?

它在我的 model which model I am saving 里面,所以当 saving is done 我是 updating related demo model's status 字段时,似乎是 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,所以我们需要不同的方法。

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 逻辑,并且如果有那么只需确保它不要更新您的父模型你的情况Lending,因为它将调用无限循环

请试试这个并告诉我们。

【讨论】:

  • 现在我收到以下错误:Failed to mass assign status attribute of Model.
  • 我在模型书中找到了添加的解决方案:protected $fillable = ['status'];
  • 感谢 Hardik,帮助我!
  • 很高兴它帮助了你,否则你也可以做$book->status = 1; $book->save(); 它也可以在没有大量分配的情况下工作:)
猜你喜欢
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 2019-06-23
  • 2019-05-16
相关资源
最近更新 更多