簡體   English   中英

如何從類別laravel獲取產品的最低價格

[英]How to get min price of products from categories laravel

我有關系的模型類別:

public function attribute()
{
    return $this->hasMany('App\Models\Attribute');
}

public function children()
{
    return $this->hasMany(self::class, 'parent_id');
}

public function products()
{
    return $this->hasMany('App\Models\Product');
}

我如何從兒童類別中獲得產品的最低價格(如果存在)。

這段代碼:

$category = Category::whereId('id', $categoryId)->first();
if($category->children) $products = $category->children()->products()->min('price'); }

不工作。 我得到錯誤:

Method Illuminate\Database\Query\Builder::products does not exist. (View: 

調用$category->children()最有可能返回一個集合。 因此,您將不得不遍歷孩子以獲得每個孩子的products

例如:

foreach ($category->children() as $cat){
    $price = $cat->products()->min('price');
    //append to price array for each child
}

children()方法的返回值是一個集合,因此您不能在該集合上調用產品。 您要么必須對集合進行迭代並獲得每個類別的最低價格,要么將您的產品組合在一起,並獲得每個組的最低價格:

$childrenWithMinPrices = $category->children()
    ->join('products', 'products.category_id', '=', 'categories.id')
    ->select('categories.*', DB::raw('MIN(products.price) AS minPrice'))
    ->groupBy('categories.id')
    ->get();

您可能必須在上面的查詢中更改表名和列名以適合您的模式。

注意:我是在腦海中寫下這個的,可能是語法錯誤。 請讓我知道是否有任何問題。

暫無
暫無

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

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