【问题标题】:How to get a total sum of quantity and send to the another table(Laravel)如何获得数量的总和并发送到另一个表(Laravel)
【发布时间】:2019-05-04 09:11:36
【问题描述】:

我想通过选择表中的typecycle_id 列来获取feeds 表中的数量总和。之后,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');

你能帮帮我吗?谢谢

【问题讨论】:

  • 如果不存在则创建新记录,否则更新它对吗?
  • 是的,先生,它会更新
  • 使用return Feed::firstOrNew([ 而不是return Feed::create([
  • 库存表怎么样?
  • 您希望它在Feedinventory 表中创建/更新?

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


【解决方案1】:

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

Feed::firstOrNew([

要得到typecycle_id 的总和:

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

Inventory表中创建OR更新记录:

$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

让我知道这是否适合你!

【讨论】:

  • 我怎样才能同时返回?
  • 什么?你需要返回什么?没找到你。
  • 我不需要return 来执行查询?
  • 如果您要返回您的视图,请参阅此答案:stackoverflow.com/a/46518751/6000629 否则只需返回 json 响应!请阅读 Laravel 基础知识文档。
  • 是的,我需要返回 feed 表,所以我返回 Feed,我只需要库存来汇总数量,这样我就可以使用另一个表来减少它
猜你喜欢
  • 2019-05-04
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 2020-04-18
相关资源
最近更新 更多