This article is provided by the thinkphp framework tutorial column to introduce and analyze the newly added virtual model function of ThinkORM. I hope it will be helpful to friends in need!
The latest version of ThinkORM adds a virtual model function. This function has appeared in ThinkPHP3.2 version, but the new version of the virtual model function is more powerful.
Previously, if virtual model operations were required, the model class could not inherit the Model class and then encapsulate its own business logic. Although it could meet some needs, it could not implement getters, modifiers and model associations. Functions, such as:
<?php namespace app\model; class User { public function getInfo() { // 业务逻辑代码 } }
The new version focuses on strengthening the virtual model. Data can only be saved in memory, and data can only be created through instantiation. The virtual model can retain most of the functions of the model, including Getters, model events, and even related operations are also more convenient for unit testing.
To use a virtual model, you only need to introduce the Virtual trait when defining the model, for example:
<?php namespace app\model; use think\Model; use think\model\concern\Virtual; class User extends Model { use Virtual; public function getInfo() { // 业务逻辑代码 } public function getStatusAttr($value) { $status = [-1=>'删除',0=>'禁用',1=>'正常',2=>'待审核']; return $status[$value]; } public function setNameAttr($value) { return strtolower($value); } public function blog() { return $this->hasMany('Blog'); } }
You do not need to have a corresponding user table in the database, but you can still carry out related data Operation, here are some simple examples.
// 创建数据 $data = [ 'id' => 8, 'name' => 'Think', 'status' => 1, ]; $user = User::create($data); // 获取数据 (支持获取器) echo $user->name; // 输出 think // 修改数据 (支持修改器) $user->name = 'ThinkPHP'; // 实际数据变成 thinkphp // 保存数据到内存 并且调用模型事件 $user->save(); // 获取关联博客数据 $blog = $user->blog()->limit(3)->select(); // 删除数据(同时删除关联博客数据) $user->together(['blog'])->delete();
Since the virtual model does not have an actual data table, you cannot perform any query operations. The following code will throw an exception:
User::find(1); // 会抛出下面的异常 // virtual model not support db query
Note that the virtual model does not support automatic timestamps function (but still supports time field formatting), if a time field is required, it needs to be passed in during instantiation.
If you define getters, modifiers and model events, they are still valid. You can test them when you have time.
Related recommendations: The latest 10 thinkphp video tutorials
The above is the detailed content of Analyze the newly added virtual model function of ThinkORM. For more information, please follow other related articles on the PHP Chinese website!