mysql - 在 Laravel 上按标签搜索 AND 和 OR

标签 mysql laravel search eloquent

我正在寻求改进关键字引擎。这是上下文。

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

查找时必须显示:

  • 网页(%)
  • 网站
  • 网络 2.0
  • 网页(%) toto
  • 网络toto
  • secret 网络
  • secret (%)

但不是在研究

  • 网络 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”搜索

最佳答案

用这个

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

关于mysql - 在 Laravel 上按标签搜索 AND 和 OR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52536165/

相关文章:

php - 如何在 PHP 中连接日期字段和时间字段

php - 使用多边形或圆形作为搜索查找纬度/经度

java - X 天后从数据库中删除项目

jsf - 搜索功能没有执行任何操作

sql - 在 MySQL 中的 HAVING 和 WHERE 子句之间使用 'OR'?

php - 如何有效地只选择 Eloquent 中属于多的关系的 ID?

php - 如何在 Windows 10 上升级 php 版本

php - Laravel excel maatwebsite 3.1 导入,excel 单元格中的日期列返回为未知格式数字。如何解决这个问题?

php - 如何在 Laravel 中使用紧凑型发送成功消息

sql - SQL 中的最佳 LIKE 搜索