Last active
April 23, 2020 08:44
-
-
Save lakuapik/a7e32d77198aabe0d1bee6bcdb044d7d to your computer and use it in GitHub Desktop.
Laravel MySQL 5.7 implementation of json array as rows
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 | |
\Illuminate\Support\Facades\Schema::create('z_user', function ($table) { | |
$table->uuid('user_id'); | |
$table->json('skills'); | |
}); | |
\Illuminate\Support\Facades\DB::table('z_user')->insert([ | |
['user_id' => \Illuminate\Support\Str::uuid(), 'skills' => '["coding", "baseball", "soccer"]'], | |
['user_id' => \Illuminate\Support\Str::uuid(), 'skills' => '["coding", "public-speaking"]'], | |
['user_id' => \Illuminate\Support\Str::uuid(), 'skills' => '["baseball", "soccer"]'], | |
]); | |
\Illuminate\Support\Facades\Schema::create('z_tmp_row', function ($table) { | |
$table->integer('row'); | |
}); | |
\Illuminate\Support\Facades\DB::table('z_tmp_row')->insert( | |
\Illuminate\Support\Collection::make(range(1, 8))->map(function ($r) { | |
return ['row' => $r]; | |
})->toArray() | |
); | |
\Illuminate\Support\Facades\DB::statement('create view z_user_skills as select user_id, json_unquote(json_extract(skills, concat("$[", z.row, "]"))) as skill from z_user inner join z_tmp_row as z on z.row < json_length(skills)'); | |
\Illuminate\Support\Facades\DB::table('z_user_skills')->where('skill', 'soccer')->get(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment