亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取用戶標簽的所有帖子?

獲取用戶標簽的所有帖子?

PHP
慕田峪9158850 2023-10-21 16:35:54
我所說的用戶標簽是指用戶可以關注標簽。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\Posttagfollow() 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 是授權用戶的關注者的用戶 ID 列表。這段代碼可以工作,它只獲取其中一個 whereIn 子句的帖子。必須有一種更好的方法來使用 Eloquent 來做到這一點,比如只從用戶標簽獲取帖子,而不是獲取標簽 id,然后循環訪問每個標簽。
查看完整描述

1 回答

?
撒科打諢

TA貢獻1934條經驗 獲得超2個贊

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()


查看完整回答
反對 回復 2023-10-21
  • 1 回答
  • 0 關注
  • 136 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號