我试图编写一个查询来从数据库中获得完整的用户饮食。问题是我无法从 diet_food 表中获取数据。这是我的表格:
这是我在控制器类中使用的查询:
$diet = Diet::with("eatingType.dietFood")->get()->find($id)->toArray();
所以当我使用 var_dump()时,它就是这样的:
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)
...
在数组中,即使我在数据库中存储了数据, diet_food 也是空的。
class Diet extends Model
{
public $table = "diet_settings";
public $timestamps = false;
public function eatingType(){
return $this->hasMany(EatingType::class);
}
}
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);
}
}
class DietFood extends Model
{
public $timestamps = false;
public $table = "diet_food";
public function eatingType(){
return $this->belongsTo(EatingType::class);
}
}
答案 0 :(得分:0)
通过遵循本指南关于枢轴来解决:http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/
同样在输出数据时,应该这样做:
$diets = Diet::with('eating')->get();
foreach($diets as $diet){
var_dump($diet->eating->toArray());
}