我将尝试尽可能地简化这个过程,以切中要害。如果您有任何其他问题,请随时让我知道。
我有两个表,如下所示:
item_centers:
| id | center | identifier | description |
|----|--------|------------|--------------------|
| 1 | 1A | 0011 | Description for 1A |
| 2 | 1B | 0022 | Description for 1B |
| 3 | 1C | 0033 | Description for 1C |一个项目中心在某种程度上可以有多个项目。表中的" identifier“列表示下面的"items”表中的标识符列。因此,中心1A可以有许多标识符为0011的“项”。
项目:
| id | identifier | description | quantity |
|----|------------|--------------------|----------|
| 1 | 0011 | Description for 1A | 250 |
| 2 | 0022 | Description for 1B | 500 |
| 3 | 0033 | Description for 1C | 750 |我有一个item center下拉列表,其中列出了"item_centers“表中按中心排列的所有项目中心。(例如: 1A)。在这个下拉列表旁边,我有一个item下拉列表,列出了包含来自"items“表的关键字的所有唯一描述。在这两个下拉列表下,我有一个文本框,允许用户输入他们试图从所选“项目”中减去的数量。
当用户选择item_center、项目描述并单击submit时,我有一个完成此操作的过程: 1.从" items“表中获取所有项目,其”标识符“与从项目中心下拉菜单中选择的项目相同。2.将第一步中检索到的所有项目的数量相加。3.从项目列表中减去用户输入的金额,从最早的开始(created_at列)。
所以对于我的问题..。
我们有许多包含数量为0的项目的项目中心。我希望能够从列表中删除所有数量为0的项目中心,这样用户就不必通过排序100个项目中心来找到数量大于0的项目中心。
这里有一个我模拟的快速示例。这显然是一种可怕的方法,因为它运行了大量的查询-而且会超时。但作为我在这里试图实现的目标的模型,它可能会工作得更好。
public function index()
{
$itemCenters = ItemCenter::select(['id', 'center', 'identifier', 'description'])
->orderBy('center', 'asc')
->orderBy('description', 'asc')
->get();
$itemDescriptions = Item::select('description')
->where('description', 'LIKE', '% .$keyword. %')
->orWhere('description', 'LIKE', '.$keyword. %')
->orWhere('description', 'LIKE', '% $.$keyword.')
->distinct('description')
->orderBy('description', 'asc')
->get();
foreach ($itemCenters as $itemCenter)
{
foreach ($itemDescriptions as $itemDescription)
{
$currentQty = Item::where('identifier', $itemCenter->identifier)
->where('description', $itemDescription->description)
->sum('quantity');
if ($currentQty <= 0)
{
$itemCenter->forget($itemCenter->id);
}
}
}
return view('pages.ItemRemoval', compact('itemCenters'), compact('itemDescriptions'));
}就像我之前说的,这真的简化了这个过程--有些事情是可以省略的。因此,如果有任何混淆,请告诉我。
发布于 2019-04-06 03:00:33
我认为最好的方法是使用laravel关系,如果不是这样的话,应该是这样的。
ItemCenter模型
public function items()
{
return $this->hasMany(Item::class);
}项目模型
public function itemCenter()
{
return $this->belongsTo(ItemCenter::class);
}因此,现在您可以在表中删除identifer和description列,如果这两个表中的这两个列相同,则将它们替换为items表中引用item_centers表中id列的item_center_id foriegn键。
现在,为了简化查询,我认为应该是这样的
$item_centers = ItemCenter::with(['items' => function($query){
$query->havingRaw('SUM(quantity) <= 0 ');
}])->get();发布于 2019-04-06 05:51:25
使用下面的查询,您基本上不再需要foreach循环来过滤$itemCenters。零个项目和相应的item_centers已经被过滤掉了。
$itemCenters = DB::table('item_centers')
->join('items', 'item_centers.identifier', '=', 'items.identifier')
->select('item_centers.id as id', 'item_centers.center as center', 'item.identifier as identifier', 'item_centers.description as description', 'items.quantity as quantity')
->where('quantity', '<>', 0)
->orderBy('center', 'asc')
->orderBy('description', 'asc')
->get();您可能需要为您的操作选择另一列(“items.created_at as created_at”)。
https://stackoverflow.com/questions/55541635
复制相似问题