duanguilin2007 2019-06-23 01:56
浏览 270
已采纳

如何根据Laravel中的数据库值循环输入字段值并插入其行?

My problem is that I want to update the quantity_served based on quantity and insert the last loop value into the last record based on the input value.

Current Database record

For example, my input value has 180.

Expected Result

My code doesn't insert the last value of loop instead of the full value of quantity.

$var = $request->get('id');
$data = bulkcorporatemodel::orderBy('id', 'asc');

foreach ($data as $item)
{
    if ($var == 0 || $var < 0)
    {
        break;
    }

    $bulkcorp = bulkcorporatemodel::find($item->id);
    $dummyHolder = $bulkcorp->quantity;
    $bulkcorp->quantity_served = $dummyHolder;
    $bulkcorp->save();

    $success_output = '<div class="alert alert-success">BULK DATA UPDATED</div>';
    $var = $var - $dummyHolder;
} 
  • 写回答

1条回答 默认 最新

  • doudang1890 2019-06-23 05:02
    关注

    (edit: I noticed that $item is in fact already in your $data collection, there is no need to find the item, it's already there. I have adapted the code accordingly and shorten the code all together :) )

    $var = $request->get('id');
    $data = bulkcorporatemodel::orderBy('id', 'asc')->get();
    foreach ($data as $bulkcorp)
    {
        if ($var <= 0)
        {
            break;
        }
    
        $bulkcorp->update(
            ['quantity_served' => $bulkcorp->quantity]
        );
    
        $success_output = '<div class="alert alert-success">BULK DATA UPDATED</div>';
        $var = $var - $bulkcorp->quantity;
    }
    

    The keyword is update()

    The thing not clear to me is what the relationship between $var and $bulkcorp->quantity is. If the var is indeed an id, you will get under 0 in one cycle and the rest of the $data collection won't be executed. If $request->get('id') is a high number, no problem.

    But, this is what you really want to achieve. Normally, we should provide you this code, but ok, for once:

    $stock = $request->get('id');
    $data = bulkcorporatemodel::orderBy('id', 'asc')->get();
    foreach ($data as $bulkcorp)
    {
        if ($stock <= 0)
        {
            break;
        }
        $stock >= $bulkcorp->quantity ? $served = $bulkcorp->quantity : $served = $stock;
    
        $bulkcorp->update(
            ['quantity_served' => $served]
        );
    
        $success_output = '<div class="alert alert-success">BULK DATA UPDATED</div>';
        $stock = $stock - $bulkcorp->quantity;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
  • ¥15 潜在扩散模型的Unet特征提取
  • ¥15 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器