From the 5.0 release, Laravel supports the conversion of JSON format data, which was previously done only to facilitate business processing, data stored in the database data type is still TEXT, but the MySQL 5.7 version began to support the native JSON data type, which will bring us great development Convenient. Laravel 5.3 also introduces a new syntax for data queries and updates based on JSON types.
Let's say we have a datasheet that contains the JSON type field:
Class Createcontactstable extends migration
{
Public function up ()
{
Schema::create (' Contacts ', function (Blueprint $table) {
$table->increments (' id ');
$table->string (' name ');
$table->json (' meta ');
$table->timestamps ();
});
}
...
}
We assume that each contact form contains some basic functionality information, such as contact names, but other attributes are flexible, and the best way to store this type of information is the JSON type-like the meta field above.
Suppose a contact form information is as follows:
{
"id": 1,
"Name": "Alphonse",
"Meta": {
"Wants_newsletter": true,
"Favorite_Color": "Red"
}
}
Now we want to get all the Favorite_Color red users, and in Laravel 5.3 We can do this:
$redLovers = db::table (' contacts ')
->where (' Meta->favorite_color ', ' Red ')
->get ();
This code will remove all records from the contacts table of the Favorite_Color property value of the Meta field to red.
You can do this if you want to update the Meta field properties:
Db::table (' contacts ')
->where (' id ', 1)
->update ([' Meta->wants_newsletter ' => false]);
It is now set to false even if the Wants_newsletter key value is empty.
Magically, in Laravel 5.3 We can query and update based on the properties of the JSON field without having to write the tedious processing code.
Note: Currently only MySQL 5.7+ supports this feature.