【问题标题】:Call to undefined method Illuminate\Database\Query\Builder::put()调用未定义的方法 Illuminate\Database\Query\Builder::put()
【发布时间】:2018-01-26 18:02:24
【问题描述】:

我正在开发一个用于家禽养殖场管理的 Laravel 应用程序。

在这里,我使用 eloquent 返回 Stockegg 表的集合,该表存储有关鸡蛋库存的数据。

但由于 Stockegg 表中不存在总库存,我正在使用总库存的初始值循环计算它。

这里是控制器:

$stockeggs = \App\Stockegg::where('farm_id', '=', $farm)->orderBy('date', 'asc')->get();

$current_stock = $initial_stock;
foreach($stockeggs as $stockegg){
    $current_stock = $current_stock + $stockegg->daily_balance;
    $stockegg->put('total_stock', $current_stock);
}

但我收到此错误:

(1/1) BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::put()

我在 mu 控制器的顶部添加了以下行:

use Illuminate\Support\Collection;

【问题讨论】:

    标签: php laravel laravel-5 eloquent php-7


    【解决方案1】:

    您有一个包含 Stockegg 模型的集合,因此当您循环该集合时,您有一个未实现 put() 方法的模型。 所以让我们添加total_stock作为属性:

        $stockeggs = \App\Stockegg::where('farm_id', '=', $farm)->orderBy('date', 'asc')->get();
    
        $current_stock = $initial_stock;
        foreach($stockeggs as $stockegg){
            $current_stock = $current_stock + $stockegg->daily_balance;
            $stockegg->total_stock= $current_stock;
            $stockegg->update()
        }
    

    【讨论】:

      【解决方案2】:

      put 不是 Eloquent 的方法。您应该编写类似这样的代码。

      foreach($stockeggs as $stockegg){
          $current_stock = $current_stock + $stockegg->daily_balance;
          $stockegg->total_stock = $current_stock;
          $stockegg->save();
      }
      

      欲了解更多信息https://laravel.com/docs/5.4/eloquent#updates

      【讨论】:

        【解决方案3】:

        我认为你应该试试这个:

        $stockeggs = \App\Stockegg::where('farm_id', '=', $farm)->orderBy('date', 'asc')->get();
        
        $current_stock = $initial_stock;
        foreach($stockeggs as $stockegg){
            $current_stock = $current_stock + $stockegg->daily_balance;
        
            //Update total stock in stockegg table
        
            \App\Stockegg::where('id', '=', $stockegg->id)->update(array('total_stock'=>$current_stock));
        }
        

        【讨论】:

          猜你喜欢
          • 2014-04-23
          • 2020-01-04
          • 2018-10-03
          • 1970-01-01
          • 2019-04-02
          • 2016-11-25
          • 2017-07-19
          • 2017-01-18
          • 2018-05-11
          相关资源
          最近更新 更多