Want to fetch data from three tables in laravel 5.2

I have a little query in which I need your help, Please have a look below.

I want to fetch all the data from the products table with some conditions like city, price, Type, category.
I can fetch all the data but I can’t fetch the category data from the product model with all other conditions.

Below is my tables and Eloquent relations. I am using Laravel 5.2.

products ->foreign_key('subcategory_id')
subcategories ->foreign_key('category_id')
category
users: ->foreign_key('product_id')
users table columns: ->city, price, product_id

Relations:
User Model:
public function product(){
    return $this->hasMany('AppProduct');
}

Product Model:
public function subcategory(){
    return $this->belongsTo('AppSubcategory', 'subcategory_id');
}


Subcategory Model:
public function product(){
    return $this->hasMany('AppProduct', 'subcategory_id');
}
public function category(){
    return $this->belongsTo('AppCategory');
}


Category Model:
public function subCategory(){
    return $this->hasMany('AppSubcategory');
}

public function product(){
   return $this->hasManyThrough('AppProduct', 'AppSubcategory');
}

Here is my query(in ProductsController.php).
$city_id, $category_id, $min_price, $max_price : demo data passed

//fetching city data
$products = Product::whereHas('user', function($query) use($city_id) {
     $query->where('city_id', $city_id);
});

//fetching category data (I am not sure about this part)
$products =  $products->whereHas('category', function($query) use($category_id) {
    $query->where('id', $category_id);
});

//fetching price data
$products = $products->where('price', '>=', $min_price)->where('price', '<=', $max_price);

//sub category filtering
$products = $products->where('subcategory_id', 1);


$products = $products->get()->toArray();

return $products;

Any help would be appreciated. Thanks in Advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think you can use with() method:

Product Model:Add the following method

public function subcategory($category_id){
    return $this->belongsTo('AppSubcategory', 'subcategory_id')->with(`category`)->where('category_id',$category_id);
}

Now in Controller, you can check if the product belongs to that category,
$products = $products->subcategory($category_id);

This will get you category data also.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x