Eloquent Raw where 使用类似条件查询 [英] Eloquent Raw where query using like condition

查看:18
本文介绍了Eloquent Raw where 使用类似条件查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个 Eloquent 原始查询来获取一些结合了标题和标签列的搜索结果.我的代码是这样的

I am using this Eloquent raw query to fetch some search results combining both caption and tags column. my code goes like this

$term="Test";
$clips=  Clip::whereRaw("caption like '%?%' OR tags like '%?%' ", array($term,$term))->get();
dd($clips);

但是使用这个我无法得到结果,因为转储显示没有结果,使用下面的代码我能够得到结果:

but using this I am not able to get results as the dump shows no results, where as using below code I am able to get results:

$term="Test";
$clips=  Clip::whereRaw("caption like '%$term%' OR tags like '%$term%' ")->get();
dd($clips);

和 dump 显示了所有 5 个预期的结果.在第一种情况下我做错了什么.

and dump shows all 5 results which are expected. What am I doing wrong in first case.

推荐答案

如果您使用准备好的语句,您应该使用 ?没有别的.如果您自己添加引号,则不应使用准备好的语句.因此,让准备好的语句处理引号并将 % 符号添加到您要插入到准备好的语句中的变量中.

If you use prepared statements, you should use a ? and nothing else. If you're adding quotes yourself, you should not be using prepared statements. So let the prepared statement take care of the quotes and add the %-sign to the variable you are inserting into the prepared statement.

$term="Test";
$clips=  Clip::whereRaw("caption like ? OR tags like ? ", array('%'.$term.'%','%'.$term.'%'))->get();
dd($clips);

顺便说一句,你也可以在没有原始位置的情况下做到这一点..

By the way, you could also do this without a raw where..

$term="Test";
$clips=Clip::where("caption","like","%".$term."%")->orWhere("tags","like","%".$term."%")->get();
dd($clips);

...我个人甚至更喜欢使用 scope 来处理这些事情.

... and personally I would even prefer to use a scope for these kind of things.

这篇关于Eloquent Raw where 使用类似条件查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆