Want to fetch data from three tables in laravel 5.2

旧时模样 提交于 2019-12-25 07:20:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/38991368/want-to-fetch-data-from-three-tables-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!