简体   繁体   English

如何从类别laravel获取产品的最低价格

[英]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. 调用$category->children()最有可能返回一个集合。 So you would have to loop over the children to get the products of each one. 因此,您将不得不遍历孩子以获得每个孩子的products

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. children()方法的返回值是一个集合,因此您不能在该集合上调用产品。 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. 请让我知道是否有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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