model
1. The definition and basic use of the model
Compared with Db operating database, Model
it is more convenient to use model classes.
In the controller
folder the same directory create a new folder model
, and then create a new Model
class, file name and the name of the database table data correspond, such as data table demo
, then the model class named Demo.php
:
<?php
namespace app\model;
use think\Model;
class Demo extends Model
{
}
Use the model class in the controller:
public function model1(){
$result = Demo::find(2);
dump($result);
}
Browser output:
This is the output model object. If you want to output data directly, you can use the toArray
method:
dump($result->toArray());
Browser output:
2. Model query and other uses
1. new model object
In addition to the direct use of static methods above, you can also operate on new
an object first . The returned model object or a collection of model objects can also be toArray
converted to an array using methods:
public function model2(){
$model = new Demo();
$result = $model->where('id','>',2)->select();
dump($result);
}
2. Model Getter
The model fetcher can modify the value of a field, or define a field that does not exist in the data table. The method name definition rule is get[字段大驼峰名]Attr
, for example getStatusTextAttr
, there is a status
field in the database, and the model
class is modified as:
<?php
namespace app\model;
use think\Model;
class Demo extends Model
{
public function getStatusTextAttr($value, $data){
$status = [
0 => '待审核',
1 => '正常',
99 => '删除'
];
return $status[$data['status']];
}
}
The controller call, the big hump naming is changed to the 下划线小写
way:
public function model2(){
$model = new Demo();
$result = $model->find(2);
dump($result->status_text); // "待审核"
dump($result->toArray());
}
But directly converted to an array, there will still be no status_text
fields:
If you want to get the 数据表中不存在的
data attributes that contain the getter processing , you can use the append
method to add, the existing fields of the data table can be processed without processing, and it will automatically return:
dump($result->append(['StatusText'])->toArray());
append
The attributes of can be 大驼峰
named or 下划线小写
method:
dump($result->append(['status_text'])->toArray());
result: