I was trying to write a single query to get full users diet from database. The problem is that I am not able to get data from the diet_food table. Here are my tables:
- diet_settings (id, total_days, etc). The basic information about the users diet.
- eating_types (id, diet_id, eating_time, etc). Information about breakfast, lunch etc.
- diet_food (id, eating_type_id, product, etc). Food related to each eating type.
This is the query that I use in my controller class:
$diet = Diet::with("eatingType.dietFood")->get()->find($id)->toArray();
So when I use var_dump() this is what it 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 the array the diet_food is empty even though I have data stored in the 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);
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire