为什么模型/变量保持其价值?

时间:2020-02-26 16:37:46

标签: php laravel eloquent

我在Laravel Framework中的代码有问题。我正在尝试做的是在模型内部出售方法。问题在于$ variable会保留其值,直到下一次代码执行为止。我应该怎么做才能像我想要的那样工作?

/// Model method.
public  function Sell()
{
    $this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
    $this->delete();   
    return null;
 }


 ///in controller 
 $user = \Auth::user();
 $user_item = UserItems::find(10);
 $user_item->Sell();

 return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.

2 个答案:

答案 0 :(得分:0)

即使您已经通过$this->delete()从数据库中删除了一条记录,$user_item变量仍会保留对填充模型的引用,直到脚本结束或销毁该变量为止。

似乎您要返回sell()函数的结果。在您的情况下应该是

///in controller 
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();

return $user_item->Sell(); 

答案 1 :(得分:0)

我不知道您要做什么,但是下面的代码可以解决您的问题-

/// Model method.
public  function Sell()
{
    $this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
    $this->delete();
    $this->ItemData = $this->ItemData->fresh() 
    return null;
 }


 ///in controller 
 $user = \Auth::user();
 $user_item = UserItems::find(10);
 $user_item->Sell();

 return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.