我希望改进一个关键字引擎。这是背景。
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“+”Web2.0“+ "Toto”+“秘密Web”
查找时必须显示:
但不是关于研究
我必须在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”。
发布于 2018-09-27 12:22:38
使用这个
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;
}https://stackoverflow.com/questions/52536165
复制相似问题