【问题标题】:Show the posts which have specific tags or categories显示具有特定标签或类别的帖子
【发布时间】:2018-03-05 12:37:44
【问题描述】:

我想显示标题中提到的具有特定标签或类别的帖子;例如,我的一篇文章有​​ 3 个标签 "php","laravel","re​​gex" 我想获取那些在多对多关系中具有 laravel 标签的帖子。

【问题讨论】:

  • 看起来您需要union 查询才能对不同的模型进行分页。
  • @hamed 您需要一个具有特定 ORMRoute 和特定标签名称的帖子列表。我说的对吗?
  • 是的@MortezaRajabi .. 没错。
  • 你不能用 eloquent 做到这一点。只是一个查询。
  • 换句话说,您希望帖子具有特定路线或标签,对吗?

标签: php sql laravel


【解决方案1】:

我更喜欢 leftJoin 而不是 whereHas,因为 whereHas 非常慢。

试试这个查询,看看有什么不同:

$posts = Post::leftJoin('post_tags', 'post_tags.post_id', '=', 'posts.id')
             ->leftJoin('post_routes', 'post_routes.post_id', '=', 'posts.id')
             ->where('name', $tagName)
             ->where('route', $routeName)
             ->get();

【讨论】:

    【解决方案2】:

    首先,确保您在模型上设置了正确的关系。然后使用Querying Relationship Existence。所以,你可以:

    $posts = Post::whereHas('tags', function ($tags) use ($tagName) {
            $tags->where('name', $tagName);
        })
        ->whereHas('ORMRoute', functions ($routes) use ($routeName) {
            $routes->where('route', $routeName);
        })
        ->get();
    

    【讨论】:

    • @hame 我不知道您的帖子和 ORMRoute 之间的关系名称是什么。所以,我使用了 ORMRoute。您应该改用它的关系名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多