0
votes

I am trying to reach the last laravel model from the first one with eloquent relationships. How can I reach the Subcategory directly from Product?

The 3 Models I have:

Product (id, category_id, etc..)

    public function categories()
    {
        return $this->belongsTo('App\Category', 'category_id');
    }

Category (id, name)

    public function products()
    {
        return $this->hasMany('App\Product', 'category_id');
    }

    public function sub_categories()
    {
        return $this->hasMany('App\SubCategory', 'category_id');
    }

SubCategory (id, category_id, name)

    public function categories()
    {
        return $this->belongsTo('App\Category', 'category_id');
    }

I would've assumed I could reach it with

Product::find(1)->categories->sub_categories;

Am I missing something obvious here?

3

3 Answers

0
votes

read this docs

Product

class Product extends Model
{
    public function SubCategory()
    {
        return $this->hasManyThrough('App\Category', 'App\SubCategory');
    }
}
0
votes

In Addition add the subCategories method on Product model and also a product is belongs to a category not categories and also always try to use camel case for the methods (subCategories)

replace your code with this

Product:

public function category()
{
    return $this->belongsTo('App\Category', 'category_id');
}

public function subCategories()
{
    return $this->category()->subCategories;
}

Category:

public function products()
{
    return $this->hasMany('App\Product', 'category_id');
}

public function subCategories()
{
    return $this->hasMany('App\SubCategory', 'category_id');
}

SubCategory:

public function categories()
{
    return $this->belongsTo('App\Category', 'category_id');
}

finally use this to get the subcategories

Product::find(1)->subCategories;
0
votes

Product::find(1)->categories is an array. You will have to loop it to get the subcategory of each category. See below

$categories = Product::find(1)->categories;
foreach ($categories as $category {
	//Get subcategories for each category
	dump($category->sub_categories);
}