Laravel 5 根据关系筛选主要数据

Laravel 5 filter main data with relationship

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

一个[user]有多个[shop],[shop]有多个分店,所以有多个[address],[shop]也有多个[type] such as alcohol,food,snack , 饮料等等。

现在我想要获取用户的商店以及所有地址和商店类型。以下是我的模型:

用户模型

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

购物Class

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

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

地址Class

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' 并且国家代码是 us 会编程吗? 我尝试了下面的代码,但对我不起作用:

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

谢谢

问题已解决,以下是我的回答:

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