我正在使用Laravel和Ajax进行搜索。所以我有一个属于标签和子类别的产品。另一方面,子类别属于类别。我想检查它们的所有属性(字段值),并检查它们是否包含给定的字符串。经过一些搜索,我发现我必须使用LIKE。这是我尝试过的:

$products = Product::where('name_en', 'LIKE', $search)->get();

但是,如果搜索字符串与值完全匹配,则将获得产品。我想匹配它是否包含它。我如何继续belongsTo关系?如何查看标签和子类别的属性?如何将所有内容链接在一起,以获得理想的结果?提前致谢。

最佳答案

您做错了一件事情,您的查询将返回完全匹配项,因为您给出了确切的字符串。但是您的查询应该是这样的。

$products = Product::where('name_en', 'LIKE', '%'.$search.'%')->get();

上面的查询将提供包含搜索字符串的产品。

如果要在关系表中搜索,则可以使用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();

这是基本示例,您可以根据需要使用它。

10-07 19:33
查看更多