使用like在两列中进行雄辩的搜索 [英] Eloquent search in two columns using like

查看:69
本文介绍了使用like在两列中进行雄辩的搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,有人可以帮忙

我需要从文本输入中搜索表中的用户

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();

我认为它是这样的,但它不起作用:D

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();


推荐答案

您可以执行以下操作来搜索所有反对姓氏和名字列的单词:

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();

这篇关于使用like在两列中进行雄辩的搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆