Laravel 5过滤主要数据与关系

时间:2015-09-26 01:51:55

标签: php mysql laravel-5.1

User : id,name,age
Shop : id,user_id,name
Address : id, shop_id, address
Shop Type : id, shop_id, type

[用户]有多个[商店],[商店]有多个分店,所以它有多[地址],[商店]也有多种类型,如酒,食品,小吃,饮料等等。

现在我希望获得所有地址和商店类型的用户商店。以下是我的模特:

用户模型

public function shop(){
     return $this->hasMany('App\Shop');
}

商店类

public function address(){
     return $this->hasMany('App\Address');
}

public function type(){
     return $this->hasMany('App\ShopType');
}

地址类

public function state(){
         return $this->hasMany('App\State');
    }

    public function city(){
         return $this->hasMany('App\City');
    }

    public function country(){
         return $this->hasMany('App\Country');
    }

我的控制

public function shop($id)
    {
            $shop = User::where("id",$id)->with('shop.address','shop.type')->first();
    if($shop){
            return response()->json(
                [
                    'shop' => $shop->shop,
                ],
                200,
                array(),
                JSON_PRETTY_PRINT
            );
    }else{
            return false;
    }

以上代码可以获取数据库中所有商店的地址和商店类型, 但我怎样才能过滤商店的类型= 'food''drink',国家/地区代码我们进行编程? 我尝试下面的代码,但不适合我:

$type = {'food','drink'};  // Example
$user = {'1'};  // Example

public function shopWithFilter($id,$type,$country)
        {
                $shop = User::where("id",$id)->with('shop.address','shop.type')->where(['shop.type.name'=>$type,'shop.address.country.code',$country])->first();
        if($shop){
                return response()->json(
                    [
                        'shop' => $shop->shop,
                    ],
                    200,
                    array(),
                    JSON_PRETTY_PRINT
                );
        }else{
                return false;
        }

由于

1 个答案:

答案 0 :(得分:0)

问题解决了,下面是我的回答:

public function shopWithFilter($id,$type,$country)
{
    $shop = User::where("id",$id)->with('shop.address','shop.type')
    ->whereHas('shop.address' function($q) use($country){
        $q->where('name',$country);
    })
    ->whereHas('shop.type' function($q) use($type){
        $q->where('name',$type);
    })
    ->first();
    if($shop){
        return response()->json(
            [
                'shop' => $shop->shop,
            ],
            200,
            array(),
            JSON_PRETTY_PRINT
        );
    }else{
        return response()->json(
            [
                'shop' => null,
            ],
            200,
            array(),
            JSON_PRETTY_PRINT
        );
    }
}