ThinkPHP6 project basic operation (7. Model)

1. The definition and basic use of the model

Compared with Db operating database, Modelit is more convenient to use model classes.
In the controllerfolder the same directory create a new folder model, and then create a new Modelclass, 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:
Insert picture description here
This is the output model object. If you want to output data directly, you can use the toArraymethod:

dump($result->toArray());

Browser output:
Insert picture description here

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 newan object first . The returned model object or a collection of model objects can also be toArrayconverted 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 statusfield in the database, and the modelclass 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_textfields:
Insert picture description here
If you want to get the 数据表中不存在的data attributes that contain the getter processing , you can use the appendmethod to add, the existing fields of the data table can be processed without processing, and it will automatically return:

dump($result->append(['StatusText'])->toArray());

appendThe attributes of can be 大驼峰named or 下划线小写method:

dump($result->append(['status_text'])->toArray());

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/zy1281539626/article/details/110354888