ThinkPHP: Usage of JSON field type (ORM)
ThinkPHP 5.1 has been officially released for some time, and I will introduce its new features to you one after another. What I want to introduce to you today is a feature that many users may not understand yet: JSON field data support.
But first of all, please note that the support for JSON field data described in this article was introduced from version V5.1.4. It is recommended to make sure to use version 5.1.9 due to the inclusion of security updates.
The definition of JSON fields in this article includes JSON types or character types where the saved data is in JSON format. Therefore, in theory, there are no requirements for database type and version except using JSON field conditional queries.
Db class operates JSON
If you do not use the model class, the Db class provides a json method to specify your data Table JSON format fields. For example, your user table has an info field of JSON type. You can use the following method to manipulate the data.
Data writing
$user['name'] = 'thinkphp'; $user['info'] = [ 'email' => 'thinkphp@qq.com', 'nickname' => '流年', ]; Db::name('user') ->json(['info']) ->insert($user);
The parameter of the json method is an array. The info field is specified in the example. In fact, multiple JSON type fields can be specified.
Data query
Query the entire JSON data.
$user = Db::name('user') ->json(['info']) ->find(1); dump($user);
The returned query result data will automatically include an array type of info data, which means that the JSON format data has been automatically processed by json_decode.
This method of querying does not strictly require the use of JSON type for the info field
If you need to query based on the value of JSON data, you can use the following method
$user = Db::name('user') ->json(['info']) ->where('info->nickname','ThinkPHP') ->find(); dump($user);
The info field must be of JSON type, and MySQL requires version 5.7 to support it
Of course, it can also support multi-level
$user = Db::name('user') ->json(['info']) ->where('info->profile->nickname','ThinkPHP') ->find(); dump($user);
Since the attribute type of the JSON field is not It will be obtained automatically, so if it is an integer data query, manual parameter binding is required, for example:
$user = Db::name('user') ->json(['info']) ->where('info->user_id', ':user_id') ->bind(['user_id' => [10, \PDO::PARAM_INT]]) ->find(); dump($user);
Data update
Complete JSON data update
$data['info'] = [ 'email' => 'kancloud@qq.com', 'nickname' => 'kancloud', ]; Db::name('user') ->json(['info']) ->where('id',1) ->update($data);
This query does not strictly require the use of JSON type for the info field
If you only update a certain value in the JSON data, you can use the following method:
$data['info->nickname'] = 'ThinkPHP'; Db::name('user') ->json(['info']) ->where('id',1) ->update($data);
It is also required that the info field must be of JSON type
Model operation JSON data
If you are using If the model operates on the database, JSON data operations will be even simpler.
We only need to add a json attribute definition to the User model class.
<?php namespace app\index\model; use think\Model; class User extends Model { // 设置json类型字段 protected $json = ['info']; }
The json attribute also supports defining multiple field names. After definition, the following JSON data operations can be performed.
Write data
Use array method to write JSON data:
$user = new User; $user->name = 'thinkphp'; $user->info = [ 'email' => 'thinkphp@qq.com', 'nickname '=> '流年', ]; $user->save();
Use object method to write JSON data
$user = new User; $user->name = 'thinkphp'; $info = new StdClass(); $info->email = 'thinkphp@qq.com'; $info->nickname = '流年'; $user->info = $info; $user->save();
Query data
The result type is different from the Db class query. The JSON field of the model will be automatically converted into an object.
$user = User::get(1); echo $user->name; // thinkphp echo $user->info->email; // thinkphp@qq.com echo $user->info->nickname; // 流年
It can also support querying JSON field data
$user = User::where('info->nickname','流年')->find(); echo $user->name; // thinkphp echo $user->info->email; // thinkphp@qq.com echo $user->info->nickname; // 流年
Same as Db class query, if the JSON attribute you need to query is an integer type, manual parameter binding is required.
$user = User::where('info->user_id',':user_id') ->bind(['user_id' => [10 ,\PDO::PARAM_INT]]) ->find(); echo $user->name; // thinkphp echo $user->info->email; // thinkphp@qq.com echo $user->info->nickname; // 流年
If you are using version V5.1.11, you can define the attribute type of the JSON field in the model class, and the corresponding type of parameter binding query will be automatically performed.
<?php namespace app\index\model; use think\Model; class User extends Model { // 设置json类型字段 protected $json = ['info']; // 设置JSON字段的类型 protected $jsonType = [ 'user_id'=>'int' ]; }
Attributes without a defined type default to string type, so string type attributes do not need to be defined.
Update data
Updating JSON data also uses objects
$user = User::get(1); $user->name = 'kancloud'; $user->info->email = 'kancloud@qq.com'; $user->info->nickname = 'kancloud'; $user->save();
If you need to do more complex operations on JSON type fields, you can also Completed by exp expression. This is waiting for everyone to discover more JSON usage.
PHP Chinese website has a large number of free ThinkPHP introductory tutorials, everyone is welcome to learn!
This article is reproduced from: https://blog.thinkphp.cn/784281
The above is the detailed content of ThinkPHP: Usage of JSON field type (ORM). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic
