雄辩的Raw在哪里使用类似条件进行查询 [英] Eloquent Raw where query using like condition

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

问题描述

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

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);

...,就我个人而言,我甚至更喜欢使用范围进行此类操作.

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

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

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