Я пытаюсь получить все продукты из вложенных категорий, используя eloquent ...
Структура БД
product
id
name
categories
id
parent_id
name
product_categories
product_id
category_id
Модели
Модель продукта
public function categories(){
return $this->belongsToMany(Category::class,'product_categories');
}
public function scopeGetCategoriesProducts($query,$category){
return $query->with('categories')
->whereHas('categories', function ($q) use ($category) {
$q->where('parent_id', $category)
->orWhere('categories.id', $category);
})->where('status',1);
}
Категория Модель
public function products(){
return $this->belongsToMany(Product::class,'product_categories');
}
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id');
}
public function childrenRecursive(){
return $this->children()->with('childrenRecursive');
}
У меня есть три уровня дерева категорий ... По коду, который у меня есть, я могу получать продукты с двух уровней ... Может кто-нибудь помочь с этим?Я твердо верю, что есть способ решить это с красноречивым.Примерно так
public function scopeGetCategoriesProducts($query,$category){
return $query->with('categories')
->whereHas('categories', function ($q) use ($category) {
$q->with('parent')
->whereHas('parent', function ($que) use ($category) {
$que->where('id',$category);
})->where('parent_id', $category)
->orWhere('categories.id', $category);
})->where('status',1);
}
Спасибо за помощь ... жду ваших предложений