首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Laravel和和OR上进行标签搜索

在Laravel和和OR上进行标签搜索
EN

Stack Overflow用户
提问于 2018-09-27 11:39:57
回答 1查看 311关注 0票数 0

我希望改进一个关键字引擎。这是背景。

3个表格:目录、contents_tags、标签

代码语言:javascript
复制
content
id  | content
8 | My content

contents_tags
id  | content_id | tag_id
1 | 8 | 1
2 | 8 | 2
3 | 8 | 3
4 | 8 | 4

tags
id | name
1 | Webs
2 | Web 2.0
3 | Toto
4 | Secret Web
5 | Titi

我试图有以下行为:

因此,带有这个标签的8个内容:" Web“+”Web2.0“+ "Toto”+“秘密Web”

查找时必须显示:

  • 网络(%)
  • Web2.0
  • 网络(%)
  • 蜘蛛网
  • 秘密网络
  • 秘密(%)

但不是关于研究

  • Web3.0

我必须在mysql中,而不是在PHP中这样做,因为我使用分页

我现在的代码是:

代码语言:javascript
复制
    public function searchByTag($q)
{
    $tag = Tag::where('name', 'LIKE', '%' . $q . '%')->get();

    if($tag->isEmpty()) {
        if ($q == trim($q) && strpos($q, ' ') !== false) {
          $q = explode(" ", $q);
          $tag = Tag::where('name', 'LIKE', $q[0] . '%')
            ->OrWhere('name', 'LIKE', $q[1] . '%')
            ->get();
        }
    }
    $query = Content::where('status', Content::STATUS_PUBLISHED);

    foreach($tag as $t) {
        $query->whereHas('tags', function ($query) use ($t) {
            $query->where('tag_id', $t->id);
        });
    }
    return !$tag->isEmpty()
        ? $query->orderBy('published_at','DESC')
        : null;
}

它适用于"web+titi“搜索或"web+2.0",但仅适用于"web”。

EN

回答 1

Stack Overflow用户

发布于 2018-09-27 12:22:38

使用这个

代码语言:javascript
复制
public function searchByTag($q)
{
    $tag = Tag::where('name', 'LIKE', '%' . $q . '%')->get();

    if($tag->isEmpty()) {
        if ($q == trim($q) && strpos($q, ' ') !== false) {
          $q = explode(" ", $q);
          $tag = Tag::where('name', 'LIKE', $q[0] . '%')
            ->OrWhere('name', 'LIKE', $q[1] . '%')
            ->get();
        }
        else
        {
             $tag = Tag::where('name', 'LIKE', $q)
                     ->get();
        }
    }
    $query = Content::where('status', Content::STATUS_PUBLISHED);

    foreach($tag as $t) {
        $query->whereHas('tags', function ($query) use ($t) {
            $query->where('tag_id', $t->id);
        });
    }
    return !$tag->isEmpty()
        ? $query->orderBy('published_at','DESC')
        : null;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52536165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档