php - 如何简化 Laravel 中的多重搜索?

标签 php laravel laravel-5

有时候我们在Laravel中使用where时会出现这样的场景,像这样:

if (!empty($request->input('user_name'))) {
    $where[] = ['user_name', 'like', "%" . $request->input('user_name') . "%"];
}
if (!empty($request->input('group_id'))) {
    $where[] = ['group_id', $request->input('group_id') ];
}
if (!empty($request->input('email'))) {
    $where[] = ['email', 'like', "%" . $request->input('email') . "%"];
}

if (!empty($request->input('mobile'))) {
    $where[] = ['mobile', 'like', "%" . $request->input('mobile') . "%"];
}
$users = User::where($where)->get();

但它太丑了,但我只想使用这个 User::search($request->only(['user_name', 'email', 'mobile']));,也许我们必须为输入名称的键名称设计一些规则,您对这种情况有什么好主意吗?谢谢。

最佳答案

您可以创建 local scope :

public function scopeSearch($q, $inputs)
{
    $where = [];

    foreach ($inputs as $key => $data) {
        $where[] = [$key, 'like', "%".$data."%"];
    }

    return $q->where($where);
}

然后使用它:

User::search($request->only(['user_name', 'email', 'mobile']))->get();

关于php - 如何简化 Laravel 中的多重搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603224/

相关文章:

php - 如何将数据库中所有表中的值插入到一张表中

php - 如何在 zend 中清理/释放数据库查询内存?

laravel - 在Laravel 5中处理TokenMismatchException

validation - Laravel 5 FormRequest 数组输入的自定义消息

php - 比较两个关联二维数组之间的差异,并在用默认值填充一个数组后,丢弃没有差异的行

php - 从mysql中的两个表中获取字段

php - 在复选框中更改管理面板上的角色

laravel - 运行一个特定的 Laravel 迁移(单个文件)

javascript - 仅显示一次弹出消息

laravel - 如何在 Laravel 5 中将数据库中的图像显示到 Blade