首页 > 解决方案 > 按用户标签获取所有帖子?

问题描述

通过用户的标签,我的意思是用户可以关注标签。我有一个名为Tagfollow Tagfollow的模型

class Tagfollow extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

除此之外,我还有 User、Tag 和 Post 模型,它们之间有以下关系。

邮政

user() belongsTo App\User 
tags() belongsToMany App\Tag

用户

posts() hasMany App\Post
tagfollow() hasMany App\Tagfollow

标签

posts() belongsToMany App\Post

我不完全确定关系是否正确。

我想获取用户关注的所有标签的 ID,然后从每个标签中获取所有帖子。

这是我到目前为止的代码。

    $user = Auth::user();
    $tag_ids= $user->tagfollow()->pluck('tag_id')->toArray();
    $tags=Tag::whereIn('id', $tag_ids)->get();
    $post_ids=[];
    foreach ($tags as $tag) {
        $post_ids = array_merge($post_ids, $tag->posts()->pluck('post_id')->toArray());
    }
    $posts =Post::whereIn('user_id', $user_ids)->whereIn('id', $post_ids)->orderby('created_at', 'desc')->paginate(20);

$user_ids 是 auth 用户的关注用户 ID 列表。

这个代码有点工作,它只获取 whereIn 子句之一的帖子。使用 Eloquent 必须有更好的方法来做到这一点,就像从用户标签获取帖子而不是获取标签 id 然后循环遍历每个标签。

标签: phplaraveleloquent

解决方案


您可以whereHas在关系查询上使用


// Get all tags id followed by user

$tagsId = $user->tagFollow()->pluck('tag_id')->toArray();

// Get all posts with corrensponding tag

$posts = Post::whereHas('tags', function ($query) use ($tagsId) {
  $query->whereIn('tags.id', $tagsId);
})->get()

推荐阅读