Created
November 5, 2021 12:46
-
-
Save ziadoz/041da1e0f54efaad961d547acbb4e482 to your computer and use it in GitHub Desktop.
MySQL 8.0 JSON MEMBER OF Laravel Eloquent Macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Database\Query\Builder; | |
$memberOf = function ($value, string $column, string $path = '$', $boolean = 'and') { | |
return $this->whereRaw( | |
sprintf( | |
'? MEMBER OF(JSON_EXTRACT(%s, "%s"))', | |
$this->getGrammar()->wrap($column), | |
$path | |
), | |
[$value], | |
$boolean | |
); | |
}; | |
Builder::macro('whereMemberOf', $memberOf); | |
Builder::macro('whereNotMemberOf', $memberOf); | |
Model::query()->whereMemberOf('a_json_column', 'value', '$[*]'); | |
Model::query()->whereNotMemberOf('a_json_column', 'value', '$.field'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks heaps, this was real helpful.