Cod*_*rts 4 php mysql search laravel eloquent
我正在使用Laravel和Ajax实现搜索.所以我有一个属于Tag和子类别的Product.另一方面,子类别属于类别.我想检查它们的所有属性(字段值)并检查它们是否包含给定的字符串.通过一些搜索我发现我必须使用LIKE.这是我尝试过的:
$products = Product::where('name_en', 'LIKE', $search)->get();
Run Code Online (Sandbox Code Playgroud)
但是,如果搜索字符串与该值完全匹配,则会获得产品.如果它包含它我想匹配.我如何处理belongsTo关系?我如何检查标签和子类别的标准?如何将所有东西连在一起,以达到理想的效果?提前致谢.
小智 22
你做错了一件事,你的查询会返回完全匹配,因为你给出了确切的字符串.但是你的查询应该是这样的.
$products = Product::where('name_en', 'LIKE', '%'.$search.'%')->get();
Run Code Online (Sandbox Code Playgroud)
以上查询将为您的产品提供包含搜索字符串的产品.
如果你想在关系表中搜索,那么你可以使用laravel方法join().但是还有一种方法,whereHas但我总是避免使用这种方法,因为它会创建非常复杂的查询.这很重.所以你可以使用join()将添加inner join关系表的方法.
以下是加入的示例:
$products = Product::join('tags', function($builder) {
$builder->on('tags.id', '=', 'products.tag_id');
// here you can add more conditions on tags table.
})
join('sub_categories', function($builder) {
$builder->on('sub_categories.id', '=', 'products.tag_id');
// here you can add more conditions on subcategories table.
})
->where('name_en', 'LIKE', '%'.$search.'%')
->get();
Run Code Online (Sandbox Code Playgroud)
这是基本示例,您可以根据您的要求使用它.
为了增加Lakhwinder Singh的答案,可能值得将其包装在可以应用于模型的范围内:
class Product extends Model
{
public function scopeSearch($query, $keywords)
{
return $query->where('name_en', 'LIKE', '%'.$keywords.'%');
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像下面这样使用该范围:
$products = Product::search($keywords)->get();
Run Code Online (Sandbox Code Playgroud)
这意味着您不必在整个应用程序中一直手动添加“ LIKE”条件。
顺便说一句,Laravel在5.3版中引入了Scout,这是Eloquent的基于驱动程序的全文本搜索扩展。