user : id,name,age shop : id,user_id,name address : id, shop_id, address shop type : id, shop_id, type
a [user] has multi [shop], , [shop] has multi branch, has multi [address], , [shop] has multi [type] such alcohol,food,snack,drink , more.
now want user's shop address , shop type. following models:
user model
public function shop(){ return $this->hasmany('app\shop'); }
shop class
public function address(){ return $this->hasmany('app\address'); } public function type(){ return $this->hasmany('app\shoptype'); }
address 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'); }
my control
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; }
code above can shop's address , shop's type in database, how can filter shop's type = 'food' , 'drink' , country code us programming? try code below, not work me :
$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; }
thanks
problem solved, below answer:
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 ); } }
Comments
Post a Comment