laravel 中 in 多列特殊查詢型別解決方案

guanguans發表於2022-07-06
SQL 查詢中有一種 in 多列特殊查詢型別,大概是這個樣子 select * from order where (id,buyer) in(( 1, '張三' ),( 2, '李四' )) and order.deleted_at is null。laravel 的查詢構建器並沒有直接支援該型別的查詢。我這邊通過查詢構建器 Macroable 新增了一個 whereIns 查詢方法方便該型別的查詢。

使用示例

<?php

use App\Models\Order;

Order::query()
    // ->whereRaw("(id,buyer) in(( 1, '張三' ),( 2, '李四' ))")
    ->whereIns(['id', 'buyer'], [
        ['buyer' => '張三', 'id' => 1],
        [2, '李四']
    ])
    ->dump()
    ->get();

// "select * from `order` where (id,buyer) in ((?,?),(?,?)) and `order`.`deleted_at` is null"
// array:4 [
//   0 => 1
//   1 => "張三"
//   2 => 2
//   3 => "李四"
// ]

新建 QueryBuilderMacro

<?php

namespace App\Support\Macros;

use Illuminate\Contracts\Support\Arrayable;

class QueryBuilderMacro
{
    public function whereIns(): callable
    {
        /* @var Arrayable|array[] $values */
        return function (array $columns, $values, string $boolean = 'and', bool $not = false) {
            /** @var \Illuminate\Database\Eloquent\Builder $this */
            $type = $not ? 'not in' : 'in';

            $rawColumns = implode(',', $columns);

            $values instanceof Arrayable and $values = $values->toArray();
            $values = array_map(function ($value) use ($columns) {
                if (array_is_list($value)) {
                    return $value;
                }

                return array_reduce($columns, function ($sortedValue, $column) use ($value) {
                    $sortedValue[$column] = $value[$column] ?? trigger_error(
                        sprintf(
                            '%s: %s',
                            'The value of the column is not found in the array.',
                            $column
                        ),
                        E_USER_ERROR
                    );

                    return $sortedValue;
                }, []);
            }, $values);

            $rawValue = sprintf('(%s)', implode(',', array_fill(0, count($columns), '?')));
            $rawValues = implode(',', array_fill(0, count($values), $rawValue));

            $raw = "($rawColumns) $type ($rawValues)";

            return $this->whereRaw($raw, $values, $boolean);
        };
    }

    public function whereNotIns(): callable
    {
        return function (array $columns, $values) {
            /** @var \Illuminate\Database\Eloquent\Builder $this */
            return $this->whereIns($columns, $values, 'and', true);
        };
    }

    public function orWhereIns(): callable
    {
        return function (array $columns, $values) {
            /** @var \Illuminate\Database\Eloquent\Builder $this */
            return $this->whereIns($columns, $values, 'or');
        };
    }

    public function orWhereNotIns(): callable
    {
        return function (array $columns, $values) {
            /** @var \Illuminate\Database\Eloquent\Builder $this */
            return $this->whereIns($columns, $values, 'or', true);
        };
    }
}

AppServiceProvider 註冊 QueryBuilderMacro 即可

<?php

namespace App\Providers;

use App\Support\Macros\QueryBuilderMacro;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    ...
    public function boot()
    {
        QueryBuilder::mixin($queryBuilderMacro = $this->app->make(QueryBuilderMacro::class));
        EloquentBuilder::mixin($queryBuilderMacro);
        Relation::mixin($queryBuilderMacro);
    }
    ...
}

原文連結

相關文章