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

问题描述 投票:1回答:3

我正在尝试用Laravel编写一个网站(当前版本是5.7),我有3个模型:Post,User和Fav。我正在使用一个简单的表单将帖子添加到“favs”表中,该表有3列; id,user_id和post_id。我想列出用户添加收藏夹的帖子我不能正确使用“hasMany”方法。

我可以使用变量; $ post-> user-> name但我无法弄清楚如何使用与“favs”表的关系。

发布模型

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

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

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);
}
php laravel eloquent has-many
3个回答
1
投票

Fav模型每个只有一个UserPost,所以你需要使用belongsTo()而不是hasMany并将方法名称改为单数。您还可以删除post()中的其他参数,因为它们是默认值。

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

加载用户已收藏的所有Posts:

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

with()方法用于eager load the relationship

现在你可以遍历Favs了:

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

1
投票

我想你可以改变你的代码的这两行

$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'));

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

如果你将更改fav表使其成为一个数据透视表只处理Post和User之间的多对多关系,你可以将它作为$user->posts,对于一个单独的模型,我认为你可以考虑像$user->favs和视图

在Fav模型中

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

0
投票

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

例:

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

Ps。:小心不要混淆hasMany和belongsToMany。

© www.soinside.com 2019 - 2024. All rights reserved.