SQL 查询中的 Laravel concat(where 条件)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25244317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel concat in query (where condition)
提问by Jonathan
I am pretty new to laravel (started today) and facing a problem building a simple query:
我对 laravel 很陌生(从今天开始)并面临构建简单查询的问题:
$query->orWhere("CONCAT(`nvp`, ' ', `vpv`)", 'LIKE', "%$this->searchNeedle%");
This line above is one of several conditions in an encapsulated query condition. I think the other lines are not necessary for this case but tell me if you need to see them.
上面的这一行是封装查询条件中的几个条件之一。我认为其他行对于这种情况不是必需的,但请告诉我您是否需要查看它们。
I found out that the developer decided to add a
我发现开发者决定添加一个
`
`
before and after the first orWhere/where param which cause the problem that I cant use a simple concat, because the line above will result in:
在第一个 orWhere/where 参数之前和之后导致我不能使用简单的连接的问题,因为上面的行将导致:
`CONCAT(`vpv`, ' ', `nvp`)` LIKE ?)'
↑ ↑
this & this
Since this is automagically added i cant remove it without overwriting a laravel-core function which i wont. Is there any SQL-based "hack" that handles these two ` ? Something in the way like 1 = 1, you know?
由于这是自动添加的,因此我无法在不覆盖我不会的 laravel 核心功能的情况下将其删除。是否有任何基于 SQL 的“hack”来处理这两个 ` ?像 1 = 1 这样的东西,你知道吗?
Maybe you have another solution for me to get the intended result, comparing one string with two rows in combination?
也许你有另一个解决方案让我得到预期的结果,将一个字符串与两行组合进行比较?
回答by user1669496
Laravel does some stuff behind the scenes like adding in the tick marks for you.
Laravel 在幕后做了一些事情,比如为你添加刻度线。
Fortunately, it also offers a couple of tools to still get the job done for you...
幸运的是,它还提供了一些工具来为您完成工作......
For this type of thing, DB::raw()
usually works really well. Try something like this...
对于这种类型的事情,DB::raw()
通常效果很好。尝试这样的事情......
$query->orWhere(DB::raw("CONCAT(`nvp`, ' ', `vpv`)"), 'LIKE', "%".$this->searchNeedle."%");
回答by Joseph Silber
Use orWhereRaw
to execute a raw where query:
使用orWhereRaw
执行原料,其中查询:
$query->orWhereRaw("CONCAT(`nvp`, ' ', `vpv`) LIKE ?", ['%'.$this->searchNeedle.'%']);