想从laravel中的三个表中提取数据5.2 [英] Want to fetch data from three tables in laravel 5.2

查看:202
本文介绍了想从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.

下面是我的表和雄辩的关系。我使用Laravel 5.2。

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 

关系:

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');
}

这是我的查询(在ProductsController.php中)

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;

任何帮助将不胜感激。感谢Advance。

Any help would be appreciated. Thanks in Advance.

推荐答案

我想你可以使用 with()方法:

产品型号:添加以下方法

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);
}

现在在Controller中,您可以检查产品是否属于该类别, br />

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.

这篇关于想从laravel中的三个表中提取数据5.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆