Laravel query using LIKE does not return any result

丶灬走出姿态 提交于 2019-12-24 20:35:12

问题


Hi guys I'm currently stuck in this issue. I'm trying to search something on DB and doesn't return any results. Below are my codes.

Search string 1 = Boston Celtics

Search string 2 = Boston Celtics Can't

DB post_title = Boston Celtics Can’t Let Bulls Loss Impact Difficult Stretch

QUERY

$data = $searchPost->where('post_title', 'like', '%'.$search.'%')
            ->orderBy('post_date', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

Search string 1 returns a result but search string 2 is not.


回答1:


Simple, because your searching different string.

Search String 2 ".. Can't .." use Straight Quotes.

'

DB post_title ".. Can’t .." use Curly Quotes.

For reference: Straight and curly quotes




回答2:


Try the following code:

1) You code might be breaking string because of ' in can't.

$data = $searchPost->where('post_title', 'like', "%{$search}%")
            ->orderBy('post_date', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();



回答3:


My first guess would be that an apostrophe might be to blame - in SQL Server the concatenation operator is "+" so you also might want to make sure that is right. Maybe try removing an apostrophe character with:

replace($search, '''', '')

Four single quotes in Microsoft SQL is an escape sequence for a single quote.




回答4:


Had the same problem before

try this

$data = $searchPost->where('post_title', 'like', '"%'.$search.'%"')
        ->orderBy('post_date', 'desc')
        ->offset($offset)
        ->limit($limit)
        ->get();

as you can see there is a " before the % at the start and another after % in the end.




回答5:


If you see carefully you Can't in your search and your DB, the ' does not look the same

Can’t vs Can't

When the ' is not the same, sure it can't be searched. Simple.




回答6:


Had to use str_replace method to change apostrophe character

$search = str_replace('-', ' ', urldecode($request->input('search')));
$search = str_replace("'", "’", $search);


来源:https://stackoverflow.com/questions/47805167/laravel-query-using-like-does-not-return-any-result

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