[英]Get all posts by a user's tags?
通過用戶的標簽,我的意思是用戶可以關注標簽。 我有一個 model 叫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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.