Rahul Mangal
Rahul Mangal

Reputation: 475

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('App\Product');
}

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


Subcategory Model:
public function product(){
    return $this->hasMany('App\Product', 'subcategory_id');
}
public function category(){
    return $this->belongsTo('App\Category');
}


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

public function product(){
   return $this->hasManyThrough('App\Product', 'App\Subcategory');
}

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.

Upvotes: 0

Views: 1463

Answers (1)

jaysingkar
jaysingkar

Reputation: 4435

I think you can use with() method:

Product Model:Add the following method

public function subcategory($category_id){
    return $this->belongsTo('App\Subcategory', '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.

Upvotes: 2

Related Questions