Laravel 5.3 Query Builder method where/update new JSON Property action syntax

Source: Internet
Author: User
Tags json contact form

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.