lets say I have the following tables
I can manage the simple relationships but I am having problems eager loading everything. what I want to do is first grab all the products parent category with all subcategories (where parent_id = the category id) and the lowest price from products prices and the number of retailers (a count on distinct product_prices.retailer_id would do it) with the product_specs and with the number of reviews and the average rating from all reviews and then the same for the subcategory without the categories.
my problem is relating retailers to products this should be done through product_prices on the retailer_id and also returning both the subcategory and parent category along with everything else using the Product model
this will give me all but the retailers and parent categories:
$this->data['products'] = Product::with('Category.parent', 'ProductPrice.retailer')->whereHas('ProductPrice', function($query){
$query->orderBy('price', 'asc'); // asc could be default, if so omit that
})->get();
this is in my Product model
public function retailers(){
return $this->hasManyThrough('ProductPrice','Retailer','id','retailer_id');
}
this in my Category model
public function parent()
{
return $this->hasOne('Category' , 'id' , 'parent_id');
}
and this is in my ProductPrice model
public function retailers()
{
return $this->hasMany('Retailer');
}
tables
retailers
| id | name |
|----|---------|
| 1 | shop1 |
|----|---------|
| 2 | shop2 |
products
| id | category_id | name | description |
|-----|---------------|--------|---------------|
| 1 | 1 | prod1 | product 1 |
|-----|---------------|--------|---------------|
| 2 | 4 | prod2 | product 2 |
product_prices
| id | retailer_id | product_id | price |
|-----|---------------|-------------|---------|
| 1 | 3 | 1 | 2.99 |
|-----|---------------|-------------|---------|
| 2 | 3 | 4 | 89.99 |
|-----|---------------|-------------|---------|
| 3 | 1 | 1 | 3.99 |
categories
| id | parent_id | name |
|----|--------------|---------|
| 1 | 0 | a cat |
|----|--------------|---------|
| 2 | 1 | subcat |
|----|--------------|---------|
| 3 | 0 | cat |
|----|--------------|---------|
| 4 | 4 | subcat2 |
Any help would be greatly appreciated
Many thanks in advance