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 name | Database prefix |
Cat | shop_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## inmodel
- 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
find to query data in the 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();public function select(){## print_r($index);
##find(6) The query failed because the database primary key name is not id3,select
Query dataselect gets multiple pieces of data and returns Is the object instance of the current model
$select = Goods::select();
public function select (){ $select = Goods::select();return $select;
}
4. Data conversiontoArray
method outputs the current model instance as an array
$select = Goods::select(6);
return $select->toArray();
}
5. Add datacreate
The static method adds data and returns the object instance of the current model
- public function create(){
'cat' => 3,$create = Goods::create([
update
Static method modifies data and returns the object instance of the current modelsave
After retrieving the data, change the fields to update the data. This method is the best way to updatedestroy
Delete according to the primary key-
#Delete method 1public function delete(){
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
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 {
$create = Goods::create([public function index(){
])->select();
return $select->toArray();}
$query->where('title','like', $v . '%');If you want to determine whether the data set is empty, you cannot directly use
empty
JudgeYou must use the
of the data set object isEmpty
Method judgment模型事件是指在进行模型的查询和写入操作的时候触发的操作行为
模型事件只在调用模型的方法生效,使用查询构造器操作是无效的
'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
##namespace app\model;use think\Model;class Goods extends Model { public function update(){ # Update method 1 $update = Goods::update( ['price'=> '99.99'], ['id'=>22]delete$user = Goods::find(23);
$user->price = '102.99';
$save = $user->save();
Return $save;
}
}
7. Delete data
Static method deletes data and returns the object instance of the current model
#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 inController
. 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 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, 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、 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) 1. Getter 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' ]; ]; } } Naming rules: 'price' => '59.99', 'add_time' => time() ]); return $create; # Return (int)$v; } } search field name Attr $select = Goods::withSearch(['title'],[ 4. Check data ##5. Change the list on the right to model example model code protected $name = 'Goods'; ## 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 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> Attribute Description 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) schema
Set the data table fields and types corresponding to the model disuse
Data table discarded fields ( Array) Attribute Description 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 ##json Set the field to JSON data jsonType Set the type of JSON field jsonAssoc Set JSON Data return array autoWriteTimestamp Automatically write the created and updated timestamp fields (off by default) createTime Create timestamp field updateTime ##deleteTime Update timestamp field defaultSoftDelete Used to define your soft delete mark field Define the default value of the soft delete field 4. Main functions of the model
' => 'New product', 'title' => 'New'
} }
##class Goods extends Model{ public function index(){ $select = Goods:: where('title','1')->select(); if(empty($select)){ echo 111; } through
class Goods extends Model{
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 ();
六、模型事件
Number Event Description Event method name 1 after_read After query onAfterRead 2 before_insert Before adding onBeforeInsert 3 after_insert After adding onAfterInsert 4 before_update before update onBeforeUpdate 5 after_update After update onAfterUpdate ##6 before_write Before writing onBeforeWrite 7 after_write After writing onAfterWrite 8 before_delete before deletion onBeforeDelete 9 after_delete After deletion onAfterDelete 10 before_restore Before recovery onBeforeRestore 11 after_restore After recovery onAfterRestore 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;
}
}