简体   繁体   中英

Laravel - how do you SELECT WHERE LIKE?

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

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

This is how the getQueryLog() looks like.

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

You have to put the % in the bindings array:

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 ORM or Query Builder

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

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

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

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

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

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

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

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

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

It's works perfect for me on laravel 5.7

Thanks

Just escaping your variable works:

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

Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM