【发布时间】:2021-02-24 22:47:42
【问题描述】:
我正在处理库存数据库。我有一些仓库和一些产品。示例数据库可以是:
请看下面的代码:
public function scopeOf($query, $warehouse, $product, $date = '')
{
$date = ($date == '' ? Carbon::today() : $date);
return $query
->where(
[
['warehouse', $warehouse],
['product', $product],
])
->whereDate('updated_at', '<=', $date)
->orderByDesc('updated_at')->take(1);
}
使用此功能,我可以通过以下方式获取一个仓库中一种产品的最新数据:
$data = Inventory::Of('w1', 'INJR')->get();
我需要列出所有仓库的所有最新数据。
我阅读了this,但它仅根据日期列出。就我而言,对于我需要的每个仓库和产品 获取最新的行。
我在 laravel 8 的开发模式下使用 SqlLite。
更新:
也许我的问题不清楚。 这是我的问题的工作功能
public function scopeOfList($query, $warehouseName = [], $productName = [], $date = '')
{
$date = ($date == '' ? Carbon::today() : $date);
$db = $query->select('product', 'warehouse')->get()->toArray();
$products = array_unique(
array_filter(
array_map(function ($n) use ($productName) {
return ($productName == [] || in_array($n['product'] ,$productName)? $n['product'] : null );
},
$db),
'strlen')
);
$warehouses = array_unique(array_map(function ($n) use ($warehouseName)
{
return ($warehouseName == '' || in_array($n['warehouse'] ,$warehouseName)? $n['warehouse'] : null );
}, $db));
$data = [];
foreach ($warehouses as $warehouse){
foreach ($products as $product){
$data[] = Inventory::
where(
[
['warehouse', $warehouse],
['product', $product],
])
->whereDate('updated_at', '<=', $date)
->orderByDesc('updated_at')->get()->first();
}
}
$inventory = array_filter($data, 'strlen');
sort($inventory);
return $inventory;
}
用途:
//get one/more product from one/more warehouse
//returns latest data only
$data = Inventory::OfList(['w1', 'w2'], ['INJR']);
//returns latest data available before 3 days
$data = Inventory::OfList(['w1', 'w2'], ['INJR', 'TP'], Carbon::now()->subDays(3));
//get one product from all warehouse
//returns latest data only
$data = Inventory::OfList([], ['INJR']);
//returns latest data available before 3 days
$data = Inventory::OfList([], ['INJR'], Carbon::now()->subDays(3));
//get all product from one warehouse
//returns latest data only
$data = Inventory::OfList(['w1']);
//returns latest data available before 3 days
$data = Inventory::OfList(['w1'], [], Carbon::now()->subDays(3));
//get all product from all warehouse
//returns latest data only
$data = Inventory::OfList();
//returns latest data available before 3 days
$data = Inventory::OfList([], [], Carbon::now()->subDays(3));
我只需要简化scopeOfList 函数以使其灵活处理inventories 表中的大量数据。如果我在每个仓库中有 500 个仓库 500 种产品,这些产品每天都会更新,那么 1 年的数据我的 php 内存将被释放,并且执行需要相当长的时间。
【问题讨论】:
-
你应该按仓库和产品分组
-
我试过了,没用
-
就我而言,对于每个仓库和产品,我需要获取最新的行。你能举个例子吗?您目前得到了什么,您的预期结果是什么?
-
@Anurat Chapanond 我已经更新了我的问题。请看一看。
标签: php database laravel eloquent