Search code examples
phplaraveleloquentrelationshiphas-and-belongs-to-many

Laravel 5.2: get models belonging to multiple models


I have two tables and a pivot table:

Table1: products
id
name

Table2: categories
id
name
parent

Pivot table: product_categories
product_id
category_id

Relationship between them is:

    product belongsToMany category (trough product_categories)
    category belongsToMany product (trough product_categories)

if its main category, than parent is 0, otherwise is an integer representing an other category's id. I have a category id, which may or may not have subcategories and may be 0 or more.

I need the list of the products belonging to the category and its subcategories. (if no category is selected, than its simple: all the products needs to be listed)

Currently I have the list of id's of the categories in an array (or in a collection):

$w = [];
$w['parent'] = (!empty($id)?$id:0);
$categories = Category::where('id', $w['parent'])->orWhere($w)->get()->toArray();

How can I do this in an elegant way? Any help would be apreciated.


Solution

  • I finally got the answer, here it is how I solved:

    $category_ids = Category::where('user_id', $user->id)->where('id', $id)->orWhere(['parent'=>$id])->pluck('id')->toArray();
    $category_ids = array_unique($category_ids);
    
    $product_ids = ProductCategory::whereIn('category_id', $category_ids)->pluck('product_id')->toArray();
    $product_ids = array_unique($product_ids);
    
    $products = Product::where('user_id', $user->id)->whereIn('id', $product_ids)->paginate(12);
    

    As long as the categories has maximum 2 levels, this works.