Laravel whereJsonContains使用jsonContains获取记录并且不包含

时间:2019-04-22 12:34:57

标签: laravel laravel-query-builder laravel-auditing

样本数据:

13 => {#531 ▼
        +"id": 956
        +"user_type": "App\User"
        +"user_id": 35
        +"event": "updated"
        +"auditable_type": "App\Video"
        +"auditable_id": 136
        +"old_values": "{"video_status_ids":"[4, 16]"}"
        +"new_values": "{"video_status_ids":"[5,16]"}"
        +"url": "http://example.com?vhjb6gsyyas"
        +"ip_address": "106.51.36.44"
        +"user_agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
        +"tags": null
        +"created_at": "2019-01-14 11:53:09"
        +"updated_at": "2019-01-14 11:53:09"
      }

代码:

 $audits = DB::table('audits')->where('auditable_type', 'LIKE', 'App%Video')->where('new_values', 'LIKE', '{"video_status_ids":"%')->where(function($query) {
        $query->whereJsonDoesntContain('old_values->video_status_ids', '4')
            ->WhereJsonDoesntContain('new_values->video_status_ids', '5');
    })->paginate(200);

在日志文件中记录的SQL查询为:

array (
    'query' => 'select * from `audits` where `auditable_type` LIKE 'App%Video' and `new_values` LIKE '{"video_status_ids":"%'and (not json_contains(`old_values`->\'$."video_status_ids"\', '"[1]"') and not json_contains(`new_values`->\'$."video_status_ids"\', '"[2]"')) and (not json_contains(`old_values`->\'$."video_status_ids"\', '4') or not json_contains(`new_values`->\'$."video_status_ids"\', '5') and not json_contains(`old_values`->\'$."video_status_ids"\', '7') or not json_contains(`new_values`->\'$."video_status_ids"\', '8') and not json_contains(`old_values`->\'$."video_status_ids"\', '10') or not json_contains(`new_values`->\'$."video_status_ids"\', '11') and not json_contains(`old_values`->\'$."video_status_ids"\', '13') or not json_contains(`new_values`->\'$."video_status_ids"\', '14') and not json_contains(`old_values`->\'$."video_status_ids"\', '16') or not json_contains(`new_values`->\'$."video_status_ids"\', '17')) limit 200 offset 0',
    'bindings' => 
    array (
      0 => 'App%Video',
      1 => '{"video_status_ids":"%',
      2 => '"[1]"',
      3 => '"[2]"',
      4 => '4',
      5 => '5',
      6 => '7',
      7 => '8',
      8 => '10',
      9 => '11',
      10 => '13',
      11 => '14',
      12 => '16',
      13 => '17',
    ),

根据我要获取的记录,有一种组合模式。像上面的代码一样,我想要记录“ old_values->video_status_ids不包含4和new_values->video_status_ids不包含5”的记录,如果还有其他组合而不是4-5(例如4-6或4-7),他们仍然应该被找回。

更新 在原始查询中,它将类似于:

SELECT * FROM audits WHERE JSON_CONTAINS(new_values->>'$.video_status_ids', '5') AND NOT JSON_CONTAINS (old_values->>'$.video_status_ids', '4') 

现在我想要在laravel查询构建器中使用它。

0 个答案:

没有答案