簡體   English   中英

在另一個表中獲得最低價格的正確方法是 laravel eloquent

[英]What is the right way to get lowest prices in another table with laravel eloquent

我有這些表格來查詢活動門票的最低價格; 事件、產品、產品庫存。 我想列出所有活動的最低價格。 我怎樣才能用 laravel 做到這一點(每張票都在產品表中,每張票在 product_inventories 中都有一些價格)。

我嘗試了一些東西,但我認為它們不是最好的解決方案。 它們在這里:我在事件 model 中定義了這個 function。

public function getLowestPriceAttribute()
{
    return ProductInventory::whereIn('product_id',
        Product::where('event_id', $this->id)
            ->pluck('id'))
        ->min('price');
}

我可以通過此查詢獲得最低價格,但像這張照片中這樣的查詢太多了。

laravel 調試欄

我嘗試過的另一件事是我沒有調用該屬性,但我已經更改了 controller 中的查詢。它只使用此代碼運行一個查詢,但我認為它在 laravel 中不正確。

$events = Event::leftJoin('products', 'event_id', 'events.id')
    ->leftJoin('product_inventories', 'product_inventories.product_id', 'products.id')
    ->groupBy('events.id')
    ->get(['events.*', \DB::raw('min(product_inventories.price) as min_price')]);

你能幫助我如何優化這段代碼嗎?

-- 一個不太重要的問題:我對每個屬性運行有 2 個查詢。 我怎樣才能把它減少到一個?

您是否在 ProductInventory 中設置了關系方法?

public function product()
{
  return $this->belongsTo(Product::class);
}

如果你有,你可以這樣做

return ProductInventory::query()
   ->with('product', function ($q) {
     return $q->where('event_id', $this->id);
   })
   ->min('price');

希望這適合您的需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM