首页 > 解决方案 > Laravel 将 Model Save() 移动到方法内部

问题描述

目前我有这样的东西在我的Controller

$stock = Stock::first();
$stock->quantity = 10;
$stock->save();

我想把它改成这样,这样逻辑就在 中Model,而不是在Controller(因为我可能想从许多不同的地方调用它):

$stock = Stock::first();
$stock->updateQuantity(10);

我尝试将其添加到我的Stock Model

public function updateQuantity($quantity){
    $this->quantity = $quantity;
    $this->save();
    return true;
}

但它不起作用,我做错了什么?

标签: phplaravellaravel-6

解决方案


推荐阅读