Home PHP Framework ThinkPHP ThinkPHP: Usage of JSON field type (ORM)

ThinkPHP: Usage of JSON field type (ORM)

Dec 16, 2019 pm 03:52 PM
json orm thinkphp Field Type

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);
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

Data update

Complete JSON data update

$data['info'] = [
'email'    => 'kancloud@qq.com',
'nickname' => 'kancloud',
];
Db::name('user')
->json(['info'])
    ->where('id',1)
->update($data);
Copy after login

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);
Copy after login

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 = [&#39;info&#39;];
}
Copy after login

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 = &#39;thinkphp&#39;;
$user->info = [
&#39;email&#39;    => &#39;thinkphp@qq.com&#39;,
    &#39;nickname &#39;=> &#39;流年&#39;,
];
$user->save();
Copy after login

Use object method to write JSON data

$user = new User;
$user->name = &#39;thinkphp&#39;;
$info = new StdClass();
$info->email = &#39;thinkphp@qq.com&#39;;
$info->nickname = &#39;流年&#39;;
$user->info = $info;
$user->save();
Copy after login

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; // 流年
Copy after login

It can also support querying JSON field data

$user = User::where(&#39;info->nickname&#39;,&#39;流年&#39;)->find();
echo $user->name; // thinkphp
echo $user->info->email; // thinkphp@qq.com
echo $user->info->nickname; // 流年
Copy after login

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(&#39;info->user_id&#39;,&#39;:user_id&#39;)
->bind([&#39;user_id&#39; => [10 ,\PDO::PARAM_INT]])
->find();
echo $user->name; // thinkphp
echo $user->info->email; // thinkphp@qq.com
echo $user->info->nickname; // 流年
Copy after login

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 = [&#39;info&#39;];
    
    // 设置JSON字段的类型
    protected $jsonType = [
    &#39;user_id&#39;=>&#39;int&#39;
    ];
}
Copy after login

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 = &#39;kancloud&#39;;
$user->info->email = &#39;kancloud@qq.com&#39;;
$user->info->nickname = &#39;kancloud&#39;;
$user->save();
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

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.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

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.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

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 tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

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.

How to use object-relational mapping (ORM) in PHP to simplify database operations? How to use object-relational mapping (ORM) in PHP to simplify database operations? May 07, 2024 am 08:39 AM

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.

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

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.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

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.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

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

See all articles