laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 31 forks source link

request DB query where() param support 'in' operator #2631

Open php-cpm opened 3 years ago

php-cpm commented 3 years ago

I am using laravel & love it.

I want to use query builder like this $db->where([['id','in',['1','2',]]])->get();

while office suggest $db->whereIn('id',['1','2',])->get();

in the 1st solution, i can create an array of query conditions and pass them to just one where() function other than linked-list style form.

I read the code src/Illuminate/Database/Query/Builder.php

some code like this:

    public $operators = [
        '=', '<', '>', '<=', '>=', '<>', '!=', '<=>',
        'like', 'like binary', 'not like', 'ilike',
        '&', '|', '^', '<<', '>>',
        'rlike', 'not rlike', 'regexp', 'not regexp',
        '~', '~*', '!~', '!~*', 'similar to',
        'not similar to', 'not ilike', '~~*', '!~~*',
    ];

may u explain why not include this feature for so long?

php-cpm commented 3 years ago

finally i found my anwser, I can add closure like this in where() function

[
  ["id","!=","1"],
  [function($query) {
    $query->whereIn('id', ['1','2','3']);
  }]
]
mserralta commented 3 years ago

I use this kind of query to store client's filters and then apply them. For example user can store a filter like "products of category A, B and C and color red".

I store in DB this filter for the user: [ ['color', 'red'], 'whereIn' => ['category', ['A', 'B', 'C']] ]

or equivalent to:

[ 'where' => ['color', 'red'], 'whereIn' => ['category', ['A', 'B', 'C']] ]

To achieve this I overrided Query\Builder method addArrayOfWheres as follow:

/**
     * Add an array of where clauses to the query.
     *
     * We override the method to support whereIn methods
     *
     * @author miquel
     * @param  array  $column
     * @param  string  $boolean
     * @param  string  $method
     * @return $this
     */
    protected function addArrayOfWheres($column, $boolean, $method = 'where')
    {
        return $this->whereNested(function ($query) use ($column, $method, $boolean) {
            foreach ($column as $key => $value) {
                if (is_numeric($key) && is_array($value)) {
                    $query->{$method}(...array_values($value));
                } else if (is_string($key) && is_array($value)) {
                    // this is my new logic
                    $query->{$key}(...array_values($value));
                } else {
                    $query->$method($key, '=', $value, $boolean);
                }
            }
        }, $boolean);
    }

Hope it helps

mserralta commented 3 years ago

But anyway, being able to write $query->where('column', 'in', [1,2,3]) would be nice to have equivalent to ->whereIn('column', [1,2,3])