调用未定义的方法Illuminate \ Database \ Query \ Builder :: put()

时间:2017-08-18 06:39:27

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

我正在开发一个用于家禽养殖场管理的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;

3 个答案:

答案 0 :(得分: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()
    }

答案 1 :(得分:1)

我想你应该试试这个:

$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));
}

希望这对你有用!!!

答案 2 :(得分:0)

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