Laravel通过数据透视表检索相关模型

时间:2016-03-01 18:47:11

标签: laravel-5

所以我对这种情况有点困惑,我有现在的关系: 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

1 个答案:

答案 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');
}