简体   繁体   中英

How to get min price of products from categories laravel

I have model category with relations:

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');
}

How I can get min price of products from children categories (if exists).

This code:

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

not working. I get error:

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

The call to $category->children() most likely returns a collection. So you would have to loop over the children to get the products of each one.

For example:

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

The return value of your children() method is a collection, therefore you can't call products on that collection. You either have to iterate the collection and get the min price for each category, or you join your products, group them and get the lowest price of each group:

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

You probably have to change table and column names in the query above to fit your schema.

Note: I wrote this off top of my head, I may got the syntax wrong. Please let me know if there are any problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM