[英]Best Way to Query This in Laravel
我將嘗試盡可能簡化此過程,以便直截了當。 如果您還有其他問題,請務必與我聯系。
我有2張桌子,如下所示:
item_centers:
| id | center | identifier | description |
|----|--------|------------|--------------------|
| 1 | 1A | 0011 | Description for 1A |
| 2 | 1B | 0022 | Description for 1B |
| 3 | 1C | 0033 | Description for 1C |
物料中心可以以某種方式包含許多物料。 該表中的“標識符”列表示以下“項目”表中的標識符列。 因此,中心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_centers”表中按中心列出了所有項目中心。 (例如:1A)。 除了該下拉菜單,我還有一個項目下拉列表,其中列出了包含“項目”表中關鍵字的所有唯一說明。 在這2個下拉菜單下,我有一個文本框,允許用戶輸入他們要從所選“項目”中減去的數量。
當用戶選擇item_center,項目說明並單擊Submit時,我將執行以下操作:1.從“ items”表中獲取所有項目,並使用與從“ item center”下拉列表中選擇的項目相同的“ identifier” 。 2.在步驟1中匯總所有已檢索項目的數量。 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'));
}
就像我之前說過的,這確實簡化了流程-事情本來可以忽略的。 因此,請讓我知道是否有任何混淆。
我認為,做到這一點的最佳方法是使用laravel關系(如果不是這樣),就像這樣
ItemCenter模型
public function items()
{
return $this->hasMany(Item::class);
}
物品模型
public function itemCenter()
{
return $this->belongsTo(ItemCenter::class);
}
因此,現在在表上,如果兩個表上的identifer和description列相同,則可以刪除它們,並在item表上使用item_center_id foriegn鍵替換它們,以替換item_centers表的id列。
現在簡化查詢,我想這會是這樣
$item_centers = ItemCenter::with(['items' => function($query){
$query->havingRaw('SUM(quantity) <= 0 ');
}])->get();
使用下面的查詢,您基本上不再需要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”)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.