将 json 字符串转换为 Laravel 查询生成器的最佳方式?

Best way convert json string to Laravel Query Builder?

我有一个过滤字符串,您认为我如何转换 laravel 查询生成器?我用了一些方法,但我不确定。

过滤器:[["id","=",2],"or",["id","=",3],"and",["name","LIKE", "%John%"]]

谢谢。

if ($request->get('filter')) {
        $filter = json_decode($request->get('filter'));

        if (gettype($filter[0]) === 'string') {
            list($field, $id) = $filter;

            $query->where($field, $id);
        } elseif (gettype($filter[0]) === 'array') {
            foreach ($filter as $value) {

                if (gettype($value) === 'string') {
                    switch ($value) {
                        case 'or':
                            //
                            break;
                        
                        case 'and':
                            //
                            break;
                    }
                } elseif (gettype($value) === 'array') {
                    list($field, $clause, $id) = $value;
                }   
            }
        }
    }

可能是这样的:

$arr = [["id","=",2],"or",["id","=",3],"and",["name","LIKE", "%John%"]];
$query = Model::query(); // build the empty query
if(size($arr) > 0){ // if there is at least 1 element
    $query->where(...$arr[0]); // apply that element
    for($i = 1; $i < size($arr); $i+=2){ // for every other entry, loop through them 2 by 2 and based of the current one, apply orWhere or where
        if($arr[$i] === "or")
            $query->orWhere(...$arr[$i+1]);
        else
            $query->where(...$arr[$i+1]);
    }
}
$result = $query->get();