从laravel中的3个表插入和更新记录

时间:2019-03-19 07:29:48

标签: laravel

我要在一次操作中使用3张表存储产品转移应用程序的记录。转移历史记录,Warehouse1StockSummaries和Warehouse2StockSummaries。

将记录存储到历史记录中是可以的,并且我向Warehouse2StockSummaries声明的增量方法也可以正常工作,除了Warehouse1StockSummaries之外。

这是我的商店功能,

    public function store(Request $request)
{
    $input = $request->all();

    $items = [];

    for($i=0; $i<= count($input['product_id']); $i++) {

        // if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
        if(!isset($input['qty_in'][$i]) || !is_numeric($input['qty_in'][$i])) continue;

        $acceptItem = [
            'product_id'    => $input['product_id'][$i],
            'transfer_qty'  => $input['qty_out'][$i],
            'user_id'       => $input['user_id'][$i]
        ];       
        array_push($items, Transferhistories::create($acceptItem));

        // dd($input);

        //update warehouse 1 summary
        $warehouse1summary = Warehouse1StockSummaries::firstOrCreate(
            ['product_id' => $input['product_id'][$i]],
            ['qty_in' => $input['qty_in'][$i],
             'qty_out' => $input['qty_out'][$i]
        ]);

        if (!$warehouse1summary->wasRecentlyCreated) {
            $warehouse1summary->increment('qty_out', $input['qty_out'][$i]);
        }


        //update warehouse 2 summary
        $stock2Summary = Warehouse2StockSummaries::firstOrCreate(
            ['product_id' => $input['product_id'][$i]], 
            ['qty_in' => $input['qty_out'][$i],'qty_out' => null]);

        if (!$stock2Summary->wasRecentlyCreated) {
            $stock2Summary->increment('qty_in', $input['qty_in'][$i]);
        } 

    }
    return redirect()->route('transferHistory.index');
}

更新仓库1摘要未达到应有的状态。

任何建议大师?提前非常感谢您!

1 个答案:

答案 0 :(得分:1)

根据laravel,firstOrCreate不会保存该值,所以在您这样做之后:

$warehouse1summary = Warehouse1StockSummaries::updateOrCreate(
            ['product_id' => $input['product_id'][$i]],
            ['qty_in' => $input['qty_in'][$i],
             'qty_out' => $input['qty_out'][$i]
        ]);

修改

方法firstOrNew将返回Model的第一个或实例。 所以你想做的是这样:

$warehouse1summary = Warehouse1StockSummaries::firstOrNew(
    ['product_id' => $input['product_id'][$i]],
    ['qty_in' => $input['qty_in'][$i],
    'qty_out' => $input['qty_out'][$i]
]);
if(isset($warehouse1summary->created_at)){
    $warehouse1summary->qty_out = $warehouse1summary->qty_out + $input['qty_out'][$i];
}
$warehouse1summary->save();