Answer the question
In order to leave comments, you need to log in
Laravel GroupBY?
Goodnight! I don't quite understand how to implement the following. There are categories, there are products, there are characteristics that are tied to products. I need to group products in different categories, according to different characteristics.
The user, adding a category, chooses by which characteristic the grouping will go.
The table looks like this
: categories:
id
title
parent
group_by (characteristic id)
Accordingly, there is a field with a category in the table with products.
products:
id
title
category
...
There is also a table with characteristics and values of characteristics
specifications:
id,
title
specifications_values:
id,
value,
specification_id
And if, let's say, I would need to group values by some field inside a table with products. No problem, everything is clear. But I don’t understand at all how I can group products by values from the specifications_values table, which are linked to the specifications table, in turn, the id of which is in the group_by field, of the table with categories.
When I declare a "relationship" of products with a category and try to group by value from the group_by field, then everything is fine.
This is what my model looks like
public function relatedCategory()
{
return $this->hasOne(ModelNomenclature::class, 'id', 'category');
}
public function getProducts()
{
return self::with('relatedCategory')->latest()->get();
}
public function index()
{
$data = [
'nomenclature' => $this->nomenclature->selfList(),
'products' => $this->products->getProducts()
];
dd( $data['products']->groupBy('relatedCategory.group_by') );
}
public function getProducts()
{
return self::with('relatedCategory.relatedSpecsValues')->latest()->get();
}
public function index()
{
$data = [
'nomenclature' => $this->nomenclature->selfList(),
'products' => $this->products->getProducts()
];
dd($data['products']->groupBy('relatedCategory.relatedSpecsValues.value'));
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question