i trying write single query full user diet database. problem not able data diet_food table. here tables:
- diet_settings (id, total_days, etc). basic information users diet.
- eating_types (id, diet_id, eating_time, etc). information breakfast, lunch etc.
- diet_food (id, eating_type_id, product, etc). food related each eating type.
this query use in controller class:
$diet = diet::with("eatingtype.dietfood")->get()->find($id)->toarray();
so when use var_dump() looks like:
array (size=7) 'id' => int 2 'user_id' => int 1 'total_days' => int 1 'total_eating' => int 6 'notes' => string '' (length=0) 'created' => string '2016-09-01' (length=10) 'eating_type' => array (size=3) 0 => array (size=6) 'id' => int 7 'diet_id' => int 2 'eating_time' => string '8:00' (length=4) 'eating_type' => string 'breakfast' (length=10) 'recommended_rate' => int 0 'diet_food' => array (size=0) ... 1 => array (size=6) 'id' => int 8 'diet_id' => int 2 'eating_time' => string '12:00' (length=5) 'eating_type' => string 'lunch' (length=14) 'recommended_rate' => int 0 'diet_food' => array (size=0) ...
in array diet_food empty though have data stored in datababase.
diet model
class diet extends model { public $table = "diet_settings"; public $timestamps = false; public function eatingtype(){ return $this->hasmany(eatingtype::class); } }
eatingtype model
class eatingtype extends model { public $timestamps = false; public $table = "eating_types"; public function dietfood(){ return $this->hasmany(dietfood::class, 'id','eating_type_id'); } public function diet(){ return $this->belongsto(diet::class); } }
dietfood model
class dietfood extends model { public $timestamps = false; public $table = "diet_food"; public function eatingtype(){ return $this->belongsto(eatingtype::class); } }
solved following guide pivots: http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/
also when outputting data should done this:
$diets = diet::with('eating')->get(); foreach($diets $diet){ var_dump($diet->eating->toarray()); }
Comments
Post a Comment