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

A[用户]有多个[商店],而[商店]又有多个分店,所以它有多个[地址],而[商店]也有酒类、食品、零食、饮料等多种[类型]。

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

用户模型

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

商店类

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

Address类

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

上面的代码可以获得数据库中所有商店的地址和商店的类型,但是我怎么能只过滤商店的类型= '食品''饮料'和国家代码是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
        );
    }
}