我想显示所有喜欢该用户的帖子。好的。我可以用这个:
$user = User::where('slug', $user->slug)
->first();
dd($user->likes);
但这不是我想做的。任何帖子都必须由版主 (->where('accept', 1)) 和 orderign (->orderBy('created_at', 'desc')) 接受。 谁知道我该怎么做? 目前我有2个模型。我的人际关系:
//Post
public function likes(){
return $this->hasMany('App\Like');
}
//Likes
public function post(){
return $this->belongsTo('App\Post');
}
//migrate of likes look like this
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('post_id');
$table->timestamps();
});
我该如何解决我的问题?
最佳答案
您可以使用“赞”作为枢纽,在用户和帖子之间建立 M:N 关系。
# User model
public function likes()
{
return $this->hasMany(Likes::class, 'user_id');
}
public function liked_posts()
{
return $this->belongsToMany(Post::class, 'likes', 'user_id', 'post_id');
}
# Likes model
public function post()
{
return $this->belongsTo(Post::class);
}
你可以像你一样设置它,用户有很多喜欢属于帖子。
// Using only likes and Likes's post relationship
$user = User::with(['likes.post' => function ($posts) {
$posts->where('accept', 1)->orderBy('created_at', 'desc');
}])->where('slug', $slug)->first();
或者您可以使用 M:N 关系。
// Using the liked_posts relationship
$user = User::with(['liked_posts' => function ($posts) {
$posts->where('accept', 1)->orderBy('created_at', 'desc');
}])->where('slug', $slug)->first();
关于mysql - 一对多关系,排序和过滤子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57382849/