所以我对这种情况有点困惑,我有现在的关系:
User
hasmany Favourite
收藏夹引用Recipe
模型
收藏夹是一个数据透视表,但当我检索给定用户的收藏夹时:
$用户>收藏夹
我得到了枢轴数据的最爱,但我想得到食谱的字段
Recipe.php :
public function favourites()
{
return $this->hasMany('App\Favourite');
}
user.php的:
public function favourites()
{
return $this->hasMany('App\Favourite');
}
Favourite.php :
public function user()
{
return $this->belongsTo('App\User','user_id');
}
public function recipes()
{
return $this->belongsTo('App\Recipe','recipe_id');
}
编辑:完全没问题,只需要致电:
@foreach($user->favourites as $favourite)
{{ $favourite->recipe->name }}
@endforeach
答案 0 :(得分:0)
你需要将你的关系设置为Has Many Through,而不是只有很多。
https://laravel.com/docs/5.2/eloquent-relationships#has-many-through
Recipe.php:
public function favourites()
{
return $this->hasManyThrough('App\Favourite', 'App\User');
}
user.php的:
public function favourites()
{
return $this->hasManyThrough('App\Favourite', 'App\Receipe');
}
Favourite.php:
public function user()
{
return $this->hasManyThrough('App\User','App\Receipe');
}