ThinkPHP6.0 model



ThinkPHP6 model

  • Please make sure you have configured the database connection information in the database configuration file

  • The model will automatically correspond to the data table. The naming rule for the model class is the name of the data table without the table prefix, using camel case naming, and the first letter is capitalized

  • The data table names automatically corresponding to the model follow the lowercase underscore specification. If your table name is in uppercase, you must set the table attribute of the model.

1. Create a model

Model nameDatabase prefix
Catshop_cat
Goods shop_goods
UserOrder shop_user_order

Table prefix setting: config/database.php In the file prefix

  • Step 1: Create a controller at the same level Directory, directory name: model

  • Step 2: Create Goods.php file## in model

#2. Model operation

In addition to calling the methods of the database class in the model (in other words, all query constructor methods of the database can be supported in the model) , you can define your own methods, so you can also regard the model as an enhanced version of the database

  • The custom method in the model file should not have the same name as the thinkphp method

  • Goods:: in the model can also use static:: keywords

  • for chain operations. You can use

1 and

find to query data in the model

find to obtain a single piece of data and return the object instance of the current model

namespace app\model;

use think\Model;

class Goods extends Model{

public function find(){

$find = Goods::find(6);

$find = Goods::where('id',7)->find();

return $find;

}

}

2.

controllerHow to call model

namespace app\controller;

use app\model\Goods;

class Index{

public function index(){

$db = new Goods( );

              $index = $db->find();  

##                 print_r($index);

##find(6) The query failed because the database primary key name is not id

3,

select

Query data

select gets multiple pieces of data and returns Is the object instance of the current model

public function select(){

$select = Goods::select();

$select = Goods::select (6);

$select = Goods::where('id','>',7)->select();

return $select;

}

4. Data conversion

toArray

method outputs the current model instance as an array

public function select (){

$select = Goods::select();

$select = Goods::select(6);

$select = Goods::where( 'id','>',7)->select();

return $select->toArray();

}

5. Add data

create

The static method adds data and returns the object instance of the current model

  • public function create(){

    $create = Goods::create([

    'cat' => 3,
  • 'title' => 'New product',

    'price' => '59.99',

    'add_time' => time()

    ]);

    echo $create->id; // You can directly obtain the auto-incremented id

    return $create;

    }

    Best practice principles for adding data: Use the create method to add data, and use saveAll to add data in batches.

    6. Modify data

    • update Static method modifies data and returns the object instance of the current model

    • save After retrieving the data, change the fields to update the data. This method is the best way to update

    ##namespace app\model;

    use think\Model;

    class Goods extends Model {

    public function update(){

    # Update method 1

    $update = Goods::update(

    ['price'=> '99.99'],

    ['id'=>22]

    $user = Goods::find(23);

    $user->price = '102.99';

    $save = $user->save();

    Return $save;

    }

    }

    7. Delete data

    delete

    Static method deletes data and returns the object instance of the current model

    • destroyDelete according to the primary key

    • public function delete(){

      #Delete method 1
    $delete = Goods::where('id',3)->delete();

    #Delete method 2

    $delete = User::destroy(4);

    return $delete;

    }

    If the TP model can only be added, deleted, checked and modified, it is better to execute it in

    Controller

    . The TP model has many features. Let’s introduce them one by one below.

    3. Model settings

    In order to better adapt to the database, the model can set the corresponding database properties in advance, and configure one data per file. surface

    AttributeDescription
    name Model name (equivalent to no data table suffix or suffix) The table name, the default is the current model class name)
    table Data table name (obtained automatically by default)
    pk Primary key name (default is id)
    schema The corresponding data table fields and types of the model
    type Fields and types that need to be automatically converted by the model
    disuse Data table discarded fields (array)

    1. name and table

    When your data table does not have a prefix, there is no difference in the definition of the name and table attributes. You can define either one

    class Goods extends Model{

    protected $name = 'Goods';

    protected $table = 'shop_goods';

    public function select(){

    $select = Goods::select();

    return $select->toArray();

    }

    }

    2 , pk Change the primary key name

    model The default primary key is id

    // You can change the primary key to shop_id try

    ALTER TABLE `ouyangke`.`shop_goods `

    CHANGE COLUMN `id` `shop_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT ' Product ID' FIRST,

    DROP PRIMARY KEY,

    ADD PRIMARY KEY ( `shop_id`) USING BTREE;

    class Goods extends Model{

    protected $name = 'Goods';

    protected $table = 'shop_goods';

    protected $pk = 'shop_id';

    public function find($id=1){

    $find = Goods::find($id);

    return $find->toArray();

    }

    }

    3, schema Set the data table fields and types corresponding to the model

    • It will be automatically obtained by default (including field type), but automatic acquisition will cause an additional query

    • Once the schema attribute is defined, it must be defined The complete data table field type

    • The type is defined according to the php data type. If it is a json type, it can be directly defined as json

    class Goods extends Model{

    protected $name = 'Goods';

    protected $table = 'shop_goods';

    protected $pk = 'shop_id';

    protected $schema = [

                                                                                                                                                                                          use using           ‐ ’ ’ s s s t- d d ,                                                               ‐  > 'string',

    'price' => 'float',

    'discount' => 'int',

    'stock' => 'int',

    'status' => 'int',

    'add_time' => 'int'

    ];

    # To define the type that needs to be automatically converted for a certain field, you can use the type attribute

    protected $type = [

    ” 'shop_id' => 'int'

    ];

    public function select(){

    $select = Goods::select();

    Return $select->toArray();

    }

    }

    4、disuse Data table discarded fields ( Array)

    class Goods extends Model{

    protected $name = 'Goods';

    protected $table = 'shop_goods';

    protected $pk = 'shop_id';

    protected $disuse = [

    'discount',

    'stock'

    ];

    public function select(){

    $select = Goods::select();

    return $select->toArray();

    }

    }

    5. Other attributes (not commonly used)

    ##json Set the field to JSON datajsonType Set the type of JSON fieldjsonAssoc Set JSON Data return arrayautoWriteTimestamp Automatically write the created and updated timestamp fields (off by default)createTime Create timestamp fieldupdateTime Update timestamp field##deleteTime defaultSoftDelete

    4. Main functions of the model

    1. Getter

    • The function of the getter is to automatically process the (original) data of the model instance

    • Naming rules: get field name Attr

    • The field name is the camel case conversion of the data table field

    class Goods extends Model{

    public function index(){

    $find = Goods::find(10);

    echo $ find->status;

                                                                                                                  use out through out out through off out off out off out off together out together out out out out straight outumble out throughrough‐from‐from‐through‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ status = [

            1=>'Open',

            2=>'Close'

            ]; ];

    }

    }

    2. Modifier

    The main function of the modifier is to set the model The data object value is processed

    Naming rules:

    set field name Attr
    • class Goods extends Model {

      public function index(){

      $create = Goods::create([
    ' => 'New product',

    'price' => '59.99',

    'add_time' => time()

    ]);

                                                                                          return $create; # Return (int)$v;

    }

    }

    3. Searcher

    Searcher It is used to encapsulate the query condition expression of the field (or search identifier) ​​

    Naming rules:

    search field name Attr

    ##class Goods extends Model{

    public function index(){

    $select = Goods::withSearch(['title'],[

      'title' => 'New'
    • ])->select();

    • return $select->toArray();
    • } public function searchTitleAttr($query,$v){

    • $query->where('title','like', $v . '%');
    }

    }

    4. Check data

    • If you want to determine whether the data set is empty, you cannot directly use empty Judge

    • You must use the of the data set object isEmpty Method judgment

    ##class Goods extends Model{

    public function index(){

    $select = Goods:: where('title','1')->select();

    if(empty($select)){

    echo 111;

    }

                                                                                                                                                                                                                                                                                          through 

    ##5. Change the list on the right to model example

    model code

    namespace app\model;

    use think\Model;

    use think\facade\Db;

    class Goods extends Model{

    protected $name = 'Goods';

    protected $table = 'shop_goods';

    public function get_all($where,$order='add_time DESC',$p=1,$total=10){

    $count = Goods::where($where)-> ;count();

                                                                                                                      using           using                 ’       ’ s ’ s ’ ‐ 1 1 t t t t t t t t t t t t t t t t t t t t t $ Total)

    -& GT; Select ();

    ## counter ($ list -& gt; isempty ()) {

    Return null;

    }

              $data = $list->toArray();

                                                                                          use ’ s using ‐ ‐ ‐$data t's t-d .                                                                                            :table('shop_cat')->where('id',$data_v['cat'])->value('name');

          }

              $arr = [

    'Count' = & GT; CEIL ($ Count/$ Total),

    'Data' = & GT; $ data

    #/ return $arr;

    }

    public function getStatusAttr($v){

    $status = [

    1=>'Open',

          2=>'Close'

          ];

              return $status[$v]; ($v){

    return date('Y-m-d',$v);

    }

    }

    controller code

    public function index(){

        $title = '商城';

        $login = '欧阳克';

        # 左侧菜单

        $menu = Db::table('shop_menu')->where('fid',0)->select();

        $left = [];

        foreach($menu as $menu_k=>$menu_v){

            $left[$menu_k] = $menu_v;

            $left[$menu_k]['lists'] = Db::table('shop_menu')->where('fid',$menu_v['id'])->select();

        }

        # 右侧列表

        $param = Request::param();

        if(isset($param['status']) && $param['status'] == 1){

            $where['status'] = 1;

        }else if(isset($param['status']) && $param['status'] == 2){

            $where['status'] = 2;

        }else{

            $where = true;

        }

        $p = isset($param['p']) ? $param['p'] : 1;


        $db = new Goods();

        $order = [

            'add_time DESC',

            'id DESC'

        ];

        $right = $db->get_all($where,$order,$p,5);

        View::assign([

            'title'  => $title,

            'login' => $login,

            'left' => $left,

            'right' => $right['data'],

            'count' => $right['count'],

            'p' => $p,

            'status' => isset($param['status']) ? $param['status'] : 0

        ]);

        return View::fetch();

    }

    html代码

    <td>{$right_v.status}</td>

    <td>{$right_v.add_time}</td>

    六、模型事件

    • 模型事件是指在进行模型的查询和写入操作的时候触发的操作行为

    • 模型事件只在调用模型的方法生效,使用查询构造器操作是无效的

    AttributeDescription
    suffix Data table suffix (default is empty)
    connection Database connection (default reading database configuration)
    query Query class name used by the model
    field Field list (array) that the model allows to be written
    strict Is it strict? Sensitive to case-sensitive fields (default is true)
    readonly Fields are read-only
    Used to define your soft delete mark field
    Define the default value of the soft delete field
    ##6 before_write Before writingonBeforeWrite7 after_write After writingonAfterWrite
    NumberEventDescriptionEvent method name
    1after_readAfter query onAfterRead
    2 before_insert Before addingonBeforeInsert
    3 after_insert After addingonAfterInsert
    4before_update before updateonBeforeUpdate
    5 after_update After updateonAfterUpdate
    8 before_delete before deletiononBeforeDelete
    9 after_delete After deletiononAfterDelete
    10 before_restore Before recoveryonBeforeRestore
    11 after_restore After recoveryonAfterRestore
    namespace app\model;
    use think\Model;
    class Goods extends Model{
        public function one_update(){
            $update = Goods::update(
                ['price'=>'99.99'],
                ['id'=>22]
            );
            return $update;
        }
        # 执行更新操作,就会之下onBeforeUpdate方法
        public static function onBeforeUpdate($goods){
            print_r($goods->price);
            return true;
        }
    }