通过Laravel AND和OR

时间:2018-09-27 11:39:58

标签: mysql laravel search eloquent

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

3个表:contents,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” +“秘密网站”

寻找时必须显示它:

  • 网站数量(%)
  • 网站
  • Web 2.0
  • 网站访问率(%)
  • 要访问的网站
  • 秘密网
  • 秘密(%)

但没有研究

  • 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”

1 个答案:

答案 0 :(得分:0)

使用此

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