如何在Laravel中基于数据库值循环输入字段值并将其插入到行中? [英] How to loop input field value and insert to its row based on the database value in Laravel?

查看:272
本文介绍了如何在Laravel中基于数据库值循环输入字段值并将其插入到行中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我想根据数量更新quantity_served,并根据输入值将最后一个循环值插入到最后一条记录中.

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.

例如,我的输入值为180.

For example, my input value has 180.

我的代码没有插入循环的最后一个值,而不是数量的完整值.

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

推荐答案

( 我注意到$ item实际上已经在您的$ data集合中,因此无需找到项目,它已经存在了.我已经相应地修改了代码,并一起缩短了代码:))

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

关键字是update()

我不清楚的是$var$bulkcorp->quantity之间的关系.如果var确实是一个id,则您将在一个周期内获得小于0的值,而$ data集合的其余部分将不会执行.如果$request->get('id')是高数字,则没问题.

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

这篇关于如何在Laravel中基于数据库值循环输入字段值并将其插入到行中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆