Laravel Like Eloquent with array value?

六眼飞鱼酱① 提交于 2019-12-05 07:04:04

问题


How can I do a Like-query, with multiple values to search for?

$searchWords = explode(' ', Input::get('search'));

Then I get an array of words that were given for the search.

How can I pass it in this:

$pages = Page::where('content', 'LIKE', '%'.$singleWord.'%')->distinct()->get();

A loop can't work, then it overwrites the $pages always; then it keeps always the latest search:

foreach($searchWords as $word){
    $pages = Page::where('content', 'LIKE', '%'.$word.'%')->distinct()->get();
}

回答1:


A loop is the solution but you only need to add the where condition without executing the query

$pages = Page::query();
foreach($searchWords as $word){
    $pages->orWhere('content', 'LIKE', '%'.$word.'%');
}
$pages = $pages->distinct()->get();



回答2:


i will code it for you :

$pages = Page->where(function($query) use($word){

foreach($searchWords as $word){
    $query->orWhere('content', 'LIKE', '%'.$word.'%');
}

})->get();

you can try that , i hope that will help :)



来源:https://stackoverflow.com/questions/27696212/laravel-like-eloquent-with-array-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!