php - 按用户标签获取所有帖子?
问题描述
通过用户的标签,我的意思是用户可以关注标签。我有一个名为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 然后循环遍历每个标签。
解决方案
您可以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()
推荐阅读
- memory - 如果程序使用整个逻辑地址空间,需要多少页表项
- linkedin - 我将如何获得链接广告的组织 URN
- ansible - 在ansible中添加用户并强制更改密码,添加新用户时重置用户密码
- sqlite - 如何在 Cargo.toml 中静态链接 sqlite3
- java - 如何在java中正确超时数据库连接
- java - 我需要浏览 IBM MQ 并获取特定类型的消息,然后从 Queue 中删除该消息
- javascript - Google 表格:API 返回未定义的 json 标记
- r - 基于字符串的 R 数据帧的条件变异
- python-3.x - 如何将三维数组重塑为二维数组
- react-select - 删除动态添加的项目 [react-select]