【问题标题】:Search by tag on Laravel AND and OR在 Laravel AND 和 OR 上按标签搜索
【发布时间】:2019-03-03 07:40:49
【问题描述】:

我希望改进关键字引擎。这是上下文。

3 个表格:内容、contents_tags、标签

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个内容: “Webs”+“Web 2.0”+“Toto”+“秘密网络”

查找时必须显示:

  • 网络(%)
  • 网站
  • Web 2.0
  • Web(%) toto
  • 网络多多
  • 秘密网络
  • 秘密(%)

但不是研究

  • Web 3.0

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

我当前的代码:

    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”

【问题讨论】:

    标签: mysql laravel search eloquent


    【解决方案1】:

    使用这个

    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;
    }
    

    【讨论】:

    • 感谢您的代码,但它不能改变任何东西。你永远不会进入 else 条件
    猜你喜欢
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2021-01-03
    相关资源
    最近更新 更多