問題描述
我是 laravel 查詢構建器的新手,我想搜索在輸入字段中輸入的多個單詞,例如,如果我輸入jhon doe",我想獲取包含 jhon 或 doe 的任何列
I am new to laravel query builder, I want to search multiple words entered in an input field for example if I type "jhon doe" I want to get any column that contains jhon or doe
我已經看到/嘗試過使用 php MySQL 的解決方案,但無法適應查詢構建器
I have seen/tried solutions using php MySQL but can't able to adapt to query builder
//1. exploding the space between the keywords
//2. using foreach apend the query together
$query = "select * from users where";
$keywordRaw = "jhon doe";
$keywords = explode(' ', $keywordRaw );
foreach ($keywords as $keyword){
$query.= " first_name LIKE '%" + $keyword +"%' OR ";
}
如何使用查詢構建器執行此操作
how do I do this using query builder
這是我到目前為止所擁有的,這樣做的正確方法是什么,
this is what i have so far, what is the proper way of doing this,
$keywordRaw = "jhon doe";
//how do I explode this words and append them along with their appropriate query
$users = User::select('users.*')
->where('first_name', 'LIKE', '%'.$keywordRaw.'%')
請幫忙,提前致謝
推薦答案
這就是您使用 QueryBuilder
的方式,但首先要補充一些注意事項:
This is how you do it with QueryBuilder
, but first some additional notes:
// user can provide double space by accident, or on purpose:
$string = 'john doe';
// so with explode you get this:
explode(' ', $string);
array(
0 => 'john',
1 => '',
2 => 'doe'
)
// Now if you go with LIKE '%'.value.'%', you get this:
select * from table where name like '%john%' or name like '%%' or ...
也就是說,您顯然不能依賴 explode
,因為在上述情況下,您將獲得所有行.
That said, you obviously can't rely on explode
because in the above case you would get all the rows.
所以,這是你應該做的:
So, this is what you should do:
$string = 'john doe';
// split on 1+ whitespace & ignore empty (eg. trailing space)
$searchValues = preg_split('/s+/', $string, -1, PREG_SPLIT_NO_EMPTY);
$users = User::where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('name', 'like', "%{$value}%");
}
})->get();
where
中有閉包,因為將 或 where
子句括在括號中是一種很好的做法.例如,如果您的 User
模型使用了 SoftDeletingScope
而您不按照我的建議去做,那么您的整個查詢就會搞砸.
There is closure in the where
because it is a good practice to wrap your or where
clauses in parentheses. For example if your User
model used SoftDeletingScope
and you would not do what I suggested, your whole query would be messed up.
這篇關于laravel 搜索多個以空格分隔的單詞的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!