laravel 判断字符串包含_Laravel - 查询模型如果值包含某个字符串(取自搜索输入)...

I am implementing a search using Laravel and Ajax. So I have a Product which belongs to a Tag and a Subcategory. On the other hand the Subcategory belongs to a Category. I want to check all of their properties (field values) and check if they contain the given string. With some searching I found out that I have to use LIKE. Here is what I tried:

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

However this will get the products if the search string matches exactly the value. I want to match if it contains it. How can I proceed with the belongsTo relationships? How can I check the propreties of Tag and Subcategory as well? How to chain everything together so I achieve the desired result? Thanks in advance.

解决方案

you are doing one thing wrong, your query returns you exact matches because you given the exact string. But your query should be like this.

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

Above query will gives your products which contains the searched string.

And if you want to search in relational tables then you can user laravel method join(). But there are one more method whereHas but I always avoiding this method, because it creates very complex query. which is very heavy. So you can use join() method which will add inner join with relational table.

Here is the example of 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();

This is the basic example, you can use this according to your requirement.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值