doue2666 2018-08-21 10:00
浏览 10

获取具有用户标记的帖子

In a Laravel app, I'm trying to implement a structure where posts are fetched that have one or more of the tags that the user has access to. I wrote the code below to do that:

$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);

This works, but feels off. So I'm wondering if there's a better way to do this?

  • 写回答

1条回答 默认 最新

  • dongweng6241 2018-08-21 10:21
    关注

    @user4992124, Will this help you.

    $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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)