Laravel Eloquent:提取所有以提供的字符串列表开头的条目 [英] Laravel Eloquent: Extract all entries that begin with a list of provided string

查看:52
本文介绍了Laravel Eloquent:提取所有以提供的字符串列表开头的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下请求从users表中提取所有条目,其中name = Albert或name = Alberto或name = Ana.

The following request extract all entries from the users table where name=Albert or name=Alberto or name=Ana.

$users = DB::table('users')
    ->whereIn('name', ['Albert', 'Alberto', 'Ana'])
    ->get();

是否有可能适应此请求以提取以以下名称开头的所有条目?

Is there is possibility to adapt this request to extract all entries that begin with the following names ?

推荐答案

在基本的 where 函数上使用like运算符:

Use the like operator on the basic where function:

$users = DB::table('users')
            ->where('name', 'like', 'T%')
            ->get();

来源

修改:基于此答案(但简化),这是一个解决您问题的简单闭包:

Based on this answer (but simplified), here is a simple closure that solves your question:

$queryStr = ['Albert', 'Alberto', 'Ana'];
$users = DB::Table('users')            
    ->where(function ($query) use ($queryStr) {
         foreach($queryStr as $q){
            $query->orwhere('name', 'like',  $q . '%');
         }      
    })->get();

这篇关于Laravel Eloquent:提取所有以提供的字符串列表开头的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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