如何通过 Laravel 中的 hasMany 关系过滤条目

How to filter entries via hasMany relationship in Laravel

我正在尝试用 Laravel(当前版本是 5.7)编写一个网站,我有 3 个模型:Post、用户和收藏夹。我正在使用一个简单的表单将 posts 添加到 "favs" table 中,其中有 3 列; ID、user_id 和 post_id。我想列出 post 用户添加的收藏夹,但我无法正确使用 "hasMany" 方法。

我可以使用像这样的变量; $post->user->name 但我不知道如何使用与 "favs" table.

的关系

Post 型号

public function user() {
    return $this->belongsTo('App\User');
}

public function favs() {
    return $this->hasMany('App\Fav');
}

最喜欢的模特

public function users() {
    return $this->hasMany('App\User');
}
public function posts() {
    return $this->hasMany('App\Post', 'post_id', 'id');
}

用户模型

public function posts() {
    return $this->hasMany('App\Post');
}

public function favs() {
    return $this->hasMany('App\Fav');
}

控制器

public function user($id){

    $favs = Fav::orderBy('post_id', 'desc')->get();
    $user = User::find($id);
    $posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
    return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
}

例如,如果一个用户有很多 Fav,您需要使用迭代块,例如 foreach。

示例:

foreach($user->favs as $fav) {
    dd($fav) // do something
}

Ps.: 注意不要混淆 hasMany 和 belongsToMany.

Fav模型只有UserPost各一个,所以需要用belongsTo()代替hasMany,并更改方法名为单数。您还可以删除 post() 中的附加参数,因为它们是默认值。

public function user() {
    return $this->belongsTo('App\User');
}
public function post() {
    return $this->belongsTo('App\Post');
}

正在加载用户收藏的所有 Post

$user->favs()->with('post')->get();

with()方法用于eager load the relationship

现在您可以遍历 Favs:

@foreach($favs as $fav)
{{ $fav->post->name }}
@endforeach

我认为你可以将这两行代码更改为

$posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);

$posts = Post::where('user_id', $id)->where('status', '4')->latest()->paginate(10);
return view('front.user', compact('user', 'posts', 'favs'));

并且为了检索用户最喜欢的帖子,

如果您要更改收藏夹 table 使其成为枢轴 table 只是为了处理 Post 和用户之间的多对多关系,您可以将其作为 $user->posts,对于一个单独的模型,我想你可以考虑像 $user->favs 和 view

这样的东西

在最喜欢的模型中

public function user() {
    return $this->belongsTo('App\User');
}
public function post() {
    return $this->belongsTo('App\Post');
}

在视野中

@foreach ( $user->favs as $fav )
    {{ $fav->post->id }}
@endforeach