【问题标题】:Using a single array to pass multiple WHERE conditions (with LIKE)使用单个数组传递多个 WHERE 条件(使用 LIKE)
【发布时间】:2015-03-16 06:29:08
【问题描述】:

理论

It's been discussed 可以使用以下代码将多个 WHERE 子句传递给 Laravel 的 Eloquent 中的单个 where() 方法:

$condition = array('field_1' => 'value_1', 'field_2' => 'value_2');
$users = User::where($conditon)->get();

上面的代码只是简单地将数组的键值对与AND 链接起来,生成这样的:

SELECT * FROM `users` WHERE field_1 = value_1 AND field_2 = value_2;

问题

上面的键值对基于相等性。 是否可以对字符串使用相同的实现,而不是 = 我们使用 LIKE

我的意思的抽象例子:

$condition = array(
                array('field_1', 'like', '%value_1%'),
                array('field_2', 'like', '%value_2%')
             );
$users = User::where($conditon)->get();

这肯定可以通过多次使用->where(...) 来完成。但是,传递单个数组是否可行?

【问题讨论】:

    标签: php laravel eloquent where sql-like


    【解决方案1】:

    不,不是。但在内部,Laravel 也只是通过循环来实现。

    Illuminate\Database\Query\Builder@where

    if (is_array($column))
    {
        return $this->whereNested(function($query) use ($column)
        {
            foreach ($column as $key => $value)
            {
                $query->where($key, '=', $value);
            }
        }, $boolean);
    }
    

    我建议你这样做:

    $condition = array(
                    'field_1' => '%value_1%',
                    'field_2' => '%value_2%'
                 );
    
    $users = User::where(function($q) use ($condition){
        foreach($condition as $key => $value){
            $q->where($key, 'LIKE', $value);
        }
    })->get();
    

    【讨论】:

    • 确实,这看起来是目前 Laravel 方式的唯一方法。非常感谢。
    • 不客气。并感谢您的编辑,复制粘贴有点快;)
    • 只是为了防止这种情况发生在其他人身上,请确保在值周围添加 %,否则它将无法正常工作!
    • 如果他们想在查询中使用 OR 而不是 AND 也可以使用 orWhere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2020-01-22
    相关资源
    最近更新 更多