Answer the question
In order to leave comments, you need to log in
How to get categories and products through a brand?
Hello. I am writing a site in laravel, but I ran into a problem:
### I have:
1. Parts
2. Brands
3. Categories
# Parts have relationships:
1. belongsTo(Brands)
2. belongsToMany(PartCategory::class, 'pivot_part_categories', 'part_id', 'category_id' );
# Brands are related:
1. hasMany(Part::class)
# Categories are related:
1. belongsToMany(Part::class, 'pivot_part_categories', 'category_id', 'part_id');
The classic output of the catalog built, show all the spare parts where the brand made such and such.
# I don't understand how to make such a directory:
We click on some brand, then we show all categories of goods that belong to spare parts that have brand == selected (on which they clicked)
# Examples of what I need:
# What I have already done and how I tried to solve the issue:
--- -------------------------------------------------- ----------
My routes look like this:
Route::get('/part/{slug}', 'Parts\[email protected]')->name('part.show');
Route::get('/category/{slug}', 'Parts\[email protected]')->name('category.show');
Route::get('brands/{brand}/{category?}', ['as' => 'brands.cats', 'uses' => 'Parts\[email protected]', function($brand = null, $category = null){}]);
public function partsByBrand($brand, $category)
{
$brand = $this->findBrandBySlug($brand); // Получил бренд
$parts = Part::with('categories')->where('parts.brand_id','=', $brand->id)->get(); // Получил запчасти привязанные к бренду и категорию каждой запчасти
return $parts;
}
Route::get('brands/{brand}/{category?}', ['as' => 'brands.cats', 'uses' => 'Parts\[email protected]', function($brand = null, $category = null){}]);
Answer the question
In order to leave comments, you need to log in
select (*, list of fields you want) from categories join parts on categories.id=parts.cat_id join brands on parts.brand=brands.id where brand.title='title', categories.title='title' and so on .d.;
$parts = Part::with('categories')->where('parts.brand_id','=', $brand->id)->get(); // Получил запчасти привязанные к бренду
foreach($parts as $part)
{
foreach($part->categories as $category)
{
// Привязываем категорию к бренду через pivot;
}
}
public function partsByBrand($brand, $category)
{
if(isset($category) && !empty($category))
{
$parts = Part::where('brand_id', '=', $brand->id)->whereHas('categories', function ($query) use ($category)
{
return $query->where('category_id', $category->id);
})->get();
return $parts;
}
$brand_categories = PartCategory::whereHas('parts', function($query) use ($brand)
{
return $query->whereHas('brand', function($query) use ($brand) {
return $query->where('brand_id', $brand->id);
});
})->orderBy('created_at', 'desc')->get();
return $brand_categories;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question