Eloquent search in two columns using like

你说的曾经没有我的故事 提交于 2020-01-05 07:01:25

问题


Hi guys can somebody help me

I need to search for users in a table from an text input

i did it if we search just by the name or by the last name but cant do it if we write both the name and the last name in the text input

this is the code when we write just the name or the last name:

$data = User::where('name', 'LIKE', '%'. $search .'%')
                 ->orWhere('firstname', 'LIKE', '%'. $search .'%')
                 ->get();

i think its something like this but it doesn't work :D

first i did split the text given from the input here is the code

$words = explode(' ', $search);
    $firstword = $words[0];
    $lastword = $words[1];


$data = User::where('name', 'LIKE', '%'. $firstword .'%')
                       ->where('firstname', 'LIKE', '%'. $lastword .'%')
                       ->get();

回答1:


You could do something like this to search for all the words against both the first name and last name columns:

// Get the search terms and define the columns we're looking at
$terms = explode(' ', $search);
$columns = ['firstname', 'lastname'];

// Start with an initial null query. I'm pretty sure Laravel expects a where before an orWhere, so this is an alright way to make that check.
$query = null;

// For each of the search terms
foreach ($terms as $term) {
    // For each column
    foreach ($columns as $column) {
        // If we have not yet started a query, start one now by applying a where to the User model. If we have started a query i.e. $query is not null, then use an orWhere
        if (is_null($query)) {
            $query = User::where($column, 'LIKE', '%' . $term . '%');
        } else {
            $query->orWhere($column, 'LIKE', '%' . $term . '%');
        }
    }
}

// Finally, get the results
$results = $query->get();



回答2:


your problem was this (orWhere instead where):

$data = User::orWhere('name', 'LIKE', '%'. $firstword .'%')
                       ->orWhere('firstname', 'LIKE', '%'. $lastword .'%')
                       ->get();



回答3:


) you can do something like this

$posts = Post::where('COLUMN_ONE','SEARCH STRING')->orWhere('COLUMN_TWO','LIKE','%'.$search)->paginate(2);

hope this helps



来源:https://stackoverflow.com/questions/41731120/eloquent-search-in-two-columns-using-like

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