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;
}
谢谢
问题解决了,下面是我的答案:
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
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句