php Laravel - 你如何选择喜欢的地方?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27863956/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:34:41  来源:igfitidea点击:

Laravel - how do you SELECT WHERE LIKE?

phpselectlaravelsql-like

提问by razvansg

If i try WHERE email = ?it works, but if i try the code bellow it doesnt. Any ideas? Thanks.

如果我尝试WHERE email = ?它的工作原理,但如果我尝试下面的代码,它就不会。有任何想法吗?谢谢。

DB::connection('operator')->select("SELECT * FROM users WHERE email LIKE '%?%'", array('test'));

This is how the getQueryLog()looks like.

这是getQueryLog()外观的样子。

  array(3) {
    ["query"]=>
    string(213) "SELECT * FROM users WHERE email LIKE '%?%'"
    ["bindings"]=>
    array(1) {
      [0]=>
      string(1) "test"
    }
    ["time"]=>
    float(1.45)
  }

回答by lukasgeiter

You have to put the %in the bindings array:

您必须将 放入%bindings 数组中:

DB::connection('operator')
    ->select("SELECT * FROM users WHERE email LIKE ?", array('%test%'));

Also it would be a lot easier to just use Laravel's Eloquent ORMor Query Builder

此外,仅使用 Laravel 的 Eloquent ORMQuery Builder会容易得多

For example that's what it would look like with the query builder:

例如,这就是查询构建器的样子:

DB::connection('operator')->table('users')->where('email', 'LIKE', '%test%')->get();

Rememberto escape any %when using a string provided by the user! Like this:

请记住%在使用用户提供的字符串时转义 any !像这样:

$escapedInput = str_replace('%', '\%', $input);

回答by damienburdo

It's works perfect for me on laravel 5.7 like this :

它在 Laravel 5.7 上非常适合我,如下所示:

$name = "the value that you want to find in the column";
Model::where("field", "LIKE", "\" . $name . "%")->get()

$nameis the part of string you want to find in the column with the concated with "%"

$name是您要在列中找到的字符串的一部分,并用“%”连接

"field"is the field of the column you can put "%" instead of "\" ( % all chars)

"field"是列的字段,您可以放置​​“%”而不是“\”(% 所有字符)

$TheResult = MyModel::where("myFieldOfMyModel", "like", "%" . $name . "%")->get();

It's works perfect for me on laravel 5.7

它在 Laravel 5.7 上非常适合我

Thanks

谢谢

回答by Herman Demsong

Just escaping your variable works:

只需转义您的变量即可:

$name = "_";
Model::where("field", "LIKE", "\" . $name . "%")->get()

Hope this helps someone.

希望这可以帮助某人。