我正在寻求改进关键字引擎。这是上下文。
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/