ThinkPHP5.1模型入门

原创 2018-12-25 10:56:17 355
摘要:<?phpnamespace app\index\model;use think\Model;use think\model\concern\SoftDelete;class User extends Model{ use SoftDelete;    //声明表名    protected $table = 'user'; 

94af9ed5f90925a7d987dcd76b573b2.jpg

<?php


namespace app\index\model;

use think\Model;

use think\model\concern\SoftDelete;

class User extends Model

{

use SoftDelete;

    //声明表名

    protected $table = 'user';


    //声明主键

    protected $pk = 'id';


    //声明删除时间的字段名

    protected $deleteTime = 'delete_time';


    //设置软删除字段的默认值

    protected $defaultSoftDelete = 0;

}




<?php

namespace app\index\controller;


use app\index\model\User as UserModel;

use think\Controller;


class Index extends Controller

{   

   //增

   public function insert(){

    $data = [

        'name' => '张三',

        'score' => 50

    ];

    $field = ['name','score'];

    // $res = UserModel::create($data,$field);

    $res = UserModel::insert($data);

    dump($res);

   }

   //删

   public function delete(){

     // $id = UserModel::destroy(10);

     // $res = UserModel::destroy(function($query){

     //    return $query->where('score','<','100');

     // });

     // dump($res);

     $res = UserModel::where('score < 100') -> delete();

     dump($res);

   }


   public function SoftDelete(){

        UserModel::destroy(24);

   }

   //改

   

   public function update(){

    // $res = UserModel::get('24');

    // $res->name = '诸葛';

    // $res->save(); 

    //  $data = ['name' => '杨'];

    //  $where = ['id' => 24];

    // UserModel::update($data,$where);

     $data = ['score' => \think\Db::raw('score-10')];

     $where =   function($query){

        return $query->where('score','>=',100);

     };

    UserModel::update($data,$where);

   }

   //查

   public function select(){

    // $res = UserModel::get(23);

    // $res = UserModel::all();

    // $res = UserModel::withTrashed()->all();

    $res = UserModel::onlyTrashed()->all();

    dump($res);

   }

}


批改老师:天蓬老师批改时间:2018-12-25 11:22:01
老师总结:不错, 模型查询的基础是,其实还是数据库查询, 底层代码仍是通过find, 和 select来实现的, 有空看一下模型源码,会很有收获的

发布手记

热门词条