【问题标题】:Eloquent search in two columns using like使用like在两列中进行雄辩的搜索
【发布时间】:2019-02-26 18:42:32
【问题描述】:

大家好,谁能帮帮我

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

如果我们只按姓名或姓氏搜索,我会这样做,但如果我们在文本输入中同时输入姓名和姓氏,则无法这样做

这是我们只写姓名或姓氏时的代码:

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

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

首先我确实拆分了输入中给出的文本,这里是代码

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


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

【问题讨论】:

  • 你试过了吗?

标签: laravel eloquent


【解决方案1】:

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

// 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】:

    你的问题是这个(或Where,而不是where):

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

    【讨论】:

    • 可以用 where() 代替第一个 orWhere()
    【解决方案3】:

    ) 你可以这样做

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

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 2020-03-19
      • 2017-10-05
      • 2020-04-26
      • 1970-01-01
      相关资源
      最近更新 更多