如何获取总数量并发送到另一个表(Laravel)

时间:2018-12-03 04:42:36

标签: php mysql database laravel laravel-query-builder

我想通过选择表中的feedstype列来获得cycle_id表中数量的总和。之后,inventory表将获得总和并保存。

FeedController.php

public function store(Request $request)
{
      //validate
      $this->validate($request, array(
          'date_input' => 'required|date',
          'delivery_number' => 'required|numeric',
          'type' => 'required|max:255',
          'quantity' => 'required|numeric'
      ));
      $input= Carbon::parse($request->get('date_input'));
      $cycle = Cycle::where('date_of_loading','<=',$input)
                     ->where('date_of_harvest','>=',$input)
                     ->first();

    return Feed::create([
        'date_input' => request('date_input'),
        'delivery_number' => request('delivery_number'),
        'type' => request('type'),
        'quantity' => request('quantity'),
        'cycle_id'     => $cycle->id ?? 0,
        'user_id'     => Auth::id()
    ]);
}

使用typecycle_id,用户将获得总数量并将其发送到inventory表。

   $overall_quantity = Feed::where('cycle_id' '=' $cycle->id ?? 0)
                           ->where('type' '=' $request->get('type'))
                           ->sum('quantity');

如果inventory表中不存在总数量,它将创建一个新列,如果总数量存在,它将添加到现有总数量中。

库存表

$table->increments('id');
$table->string('type');
$table->integer('overall_quantity);
$table->unsignedInteger('cycle_id');
$table->unsignedInteger('user_id');

你能帮我吗?谢谢

1 个答案:

答案 0 :(得分:1)

要创建或更新记录,请使用Laravel firstOrNew方法,例如:

Feed::firstOrNew([

要获取typecycle_id的总和:

$sum = request('type') + $cycle->id;

Inventory表中创建或更新记录:

$createOrUpdateInventory = Inventory::firstOrNew([ 
                                // Your array data to create/update
                           ]);

quantityfeed表中:

$createNewFeed = Feed::create([ 
                  // Your array data you want to create
                 ]);

根据您的问题进行编辑,

从库存中检索数量,如果不存在则创建它...

$inventory = Inventory::firstOrCreate(['overall_quantity' => $overall_quantity], ['type' => request('type'), 'cycle_id' => $cycle->id]);

有关更多信息:https://laravel.com/docs/5.5/eloquent#inserting-and-updating-models

让我知道这是否适合您!