簡體   English   中英

提取帶有用戶標簽的帖子

[英]Fetch posts that have a tag that the user has as well

在Laravel應用中,我試圖實現一種結構,在該結構中,獲取具有用戶有權訪問的一個或多個標簽的帖子。 我寫了下面的代碼來做到這一點:

$query = new Posts();
if (count(Auth::user()->tags) > 0) {
   $query = $query->whereHas('tags', function ($q) {
        $i = 0;
        foreach (Auth::user()->tags as $tag) {
            if ($i == 0) {
                $q->where('title', '=', $tag->title);
            } else {
                $q->orWhere('title', '=', $tag->title);
            }
            $i++;
        }
    });
}
$posts = $query->where('isTemplate', true)->orderBy($key, $order)->paginate(15);

這可行,但感覺不佳。 所以我想知道是否有更好的方法來做到這一點?

@ user4992124,這對您有幫助嗎?

$query = Posts::query()
              ->where('isTemplate', true)
              ->orderBy($key, $order);
if (Auth::user()->tags->isNotEmpty()) {
  $tags = Auth::user()
                ->tags
                ->pluck('title')
                ->toArray();
  $query = $query->whereIn('tags', $tags);
}
$posts = $query->paginate(15);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM