search
HomePHP FrameworkThinkPHPThinkPHP: Usage of JSON field type (ORM)

ThinkPHP: Usage of JSON field type (ORM)

Dec 16, 2019 pm 03:52 PM
jsonormthinkphpField 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);

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

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();

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();

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(&#39;info->nickname&#39;,&#39;流年&#39;)->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(&#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; // 流年

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;
    ];
}

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();

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
This article is reproduced at:ThinkPHP官网. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor