thinkphp5.0初入模型,实例


user模型

 1 <?php
 2 namespace app\index\model;
 3 
 4 use think\Model;
 5 
 6 class User extends Model
 7 {
 8     protected $pk = 'username';
 9 
10 //     protected $autoWriteTimestamp = true;
11 //     protected $autoWriteTimestamp = 'datetime';
12 
13 
14     // 定义时间戳字段名
15     protected $createTime = 'createat';
16     protected $updateTime = 'updateat';
17     // 关闭自动写入update_time字段
18 //     protected $updateTime = false;
19 
20     //设置只读字段
21     protected $readonly = ['username','grade'];
22     //类型转换
23     protected $type = [
24         'createat'  =>  'datetime',
25         'updateteat'  =>  'datetime',
26     ];
27         //获取器
28     public function getGradeAttr($value)
29     {
30         $grade = [1=>'超级管理员',2=>'普通管理员',3=>'普通用户'];
31         return $grade[$value];
32     }
33 
34     //自动完成
35 //     protected $auto = ['username', 'ip'];
36 //     protected $insert = ['status' => 1];
37 //     protected $update = [];
38 
39 //     protected function setNameAttr($value)
40 //     {
41 //         return strtolower($value);
42 //     }
43 
44 //     protected function setIpAttr()
45 //     {
46 //         return request()->ip();
47 //     }
48 
49 }

验证器user

<?php
namespace app\index\validate;

use think\Validate;

class User extends Validate
{
    protected $rule = [
        'name'  =>  'require|min:25',
        'email' =>  'email',
    ];
}

?>

使用时候

 
 

<?php
namespace app\index\controller;

 
 

use think\Db;
use think\Controller;
use app\index\model\User;

 
 

class Index extends Controller
{

 
 

public function index()
{
// $data = [
// 'name'=>'thinkphp',
// 'email'=>'thinkphpqq.com'
// ];

 
 

// $validate = validate('User');
// if(!$validate->check($data)){
// dump($validate->getError());
// }
$data = Db::view('word', 'wordId,wordEn,wordCh')->view('cf', 'cfName', 'word.wordCfId=cf.cfId', 'LEFT')->select();

 
 

// dump(cache('user'));
// 实例化User模型

 
 

// 根据表单提交的POST数据创建数据对象
// $data['name'] = 'ThinkPHP';
// $data['email'] = 'ThinkPHP@gmail.com';

 
 

// $user = User::get('ys');
// $user->username = 'thinkphp';
// $user->grade = '6';
// $user->isLimit = '3';
// $user->save();

 
 

// $list = User::all();

 
 

$user = new User();
// $user->username='test';
// $user->grade=2;
// $map['username']='jkll';
// $user->save($map);
//查询数据集
$list=$user
->limit(10)
->select();
// foreach ($list as $l){

 
 

// dump($l['updateat'].$l['username']);
// }
return json($list);

 
 


}
}

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM