ThinkPHP6.0 模型
模型會自動對應(yīng)數(shù)據(jù)表,模型類的命名規(guī)則是除去表前綴的數(shù)據(jù)表名稱,采用駝峰法命名,并且首字母大寫.
ThinkPHP6 模型
請確保你已經(jīng)在數(shù)據(jù)庫配置文件中配置了數(shù)據(jù)庫連接信息
模型會自動對應(yīng)數(shù)據(jù)表,模型類的命名規(guī)則是除去表前綴的數(shù)據(jù)表名稱,采用駝峰法命名,并且首字母大寫
模型自動對應(yīng)的數(shù)據(jù)表名稱都是遵循小寫+下劃線規(guī)范,如果你的表名有大寫的情況,必須通過設(shè)置模型的table屬性。
一、創(chuàng)建模型
模型名 | 數(shù)據(jù)庫前綴 |
Cat | shop_cat |
Goods | shop_goods |
UserOrder | shop_user_order |
表前綴設(shè)置:config/database.php
文件里 prefix
第一步:創(chuàng)建一個跟控制器平級的目錄,目錄名:
model
第二步:在
model
創(chuàng)建Goods.php
文件
二、模型操作
在模型中除了可以調(diào)用數(shù)據(jù)庫類的方法之外(換句話說,數(shù)據(jù)庫的所有查詢構(gòu)造器方法模型中都可以支持),可以定義自己的方法,所以也可以把模型看成是數(shù)據(jù)庫的增強版
模型文件里的自定義方法,不要和 thinkphp 方法一樣名稱
模型里的
Goods::
也可以用static::
關(guān)鍵詞鏈式操作,都可以在模型里使用
1、find
查詢數(shù)據(jù)
find 獲取單條數(shù)據(jù),返回的是當(dāng)前模型的對象實例
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、controller
怎么調(diào)用model
namespace app\controller;
use app\model\Goods;
class Index{
public function index(){
$db = new Goods();
$index = $db->find();
print_r($index);
}
}
find(6) 查詢失敗,是因為數(shù)據(jù)庫主鍵名稱不是 id
3、select
查詢數(shù)據(jù)
select 獲取多條數(shù)據(jù),返回的是當(dāng)前模型的對象實例
public function select(){
$select = Goods::select();
$select = Goods::select(6);
$select = Goods::where('id','>',7)->select();
return $select;
}
4、數(shù)據(jù)轉(zhuǎn)換
toArray
方法將當(dāng)前的模型實例輸出為數(shù)組
public function select(){
$select = Goods::select();
$select = Goods::select(6);
$select = Goods::where('id','>',7)->select();
return $select->toArray();
}
5、增加數(shù)據(jù)
create
靜態(tài)方法添加數(shù)據(jù),返回的是當(dāng)前模型的對象實例
public function create(){
$create = Goods::create([
'cat' => 3,
'title' => '新商品',
'price' => '59.99',
'add_time' => time()
]);
echo $create->id; // 可以直接獲取自增id
return $create;
}
新增數(shù)據(jù)的最佳實踐原則:使用create方法新增數(shù)據(jù),使用saveAll批量新增數(shù)據(jù)。
6、修改數(shù)據(jù)
update
靜態(tài)方法修改數(shù)據(jù),返回的是當(dāng)前模型的對象實例save
在取出數(shù)據(jù)后,更改字段更新數(shù)據(jù)。這種方式是最佳的更新方式
namespace app\model;
use think\Model;
class Goods extends Model{
public function update(){
# 更新方式1
$update = Goods::update(
['price'=>'99.99'],
['id'=>22]
);
return $update;
# 更新方式2
$user = Goods::find(23);
$user->price = '102.99';
$save = $user->save();
return $save;
}
}
7、刪除數(shù)據(jù)
delete
靜態(tài)方法刪除數(shù)據(jù),返回的是當(dāng)前模型的對象實例destroy
根據(jù)主鍵刪除
public function delete(){
# 刪除方法1
$delete = Goods::where('id',3)->delete();
# 刪除方法2
$delete = User::destroy(4);
return $delete;
}
TP模型如果只能增刪查改,不如在 Controller
執(zhí)行了。TP模型很多特點,下面為大家一一介紹
三、模型設(shè)置
為了和數(shù)據(jù)庫更好的適配,模型可以提前設(shè)置對應(yīng)的數(shù)據(jù)庫屬性,一個文件配置一個數(shù)據(jù)表
屬性 | 描述 |
name | 模型名(相當(dāng)于不帶數(shù)據(jù)表前后綴的表名,默認為當(dāng)前模型類名) |
table | 數(shù)據(jù)表名(默認自動獲?。?/td> |
pk | 主鍵名(默認為 id ) |
schema | 模型對應(yīng)數(shù)據(jù)表字段及類型 |
type | 模型需要自動轉(zhuǎn)換的字段及類型 |
disuse | 數(shù)據(jù)表廢棄字段(數(shù)組) |
1、name和table
當(dāng)你的數(shù)據(jù)表沒有前綴的時候,name和table屬性的定義是沒有區(qū)別的,定義任何一個即可
class Goods extends Model{
protected $name = 'Goods';
protected $table = 'shop_goods';
public function select(){
$select = Goods::select();
return $select->toArray();
}
}
2、pk 改變主鍵名稱
model 默認的主鍵是id
// 可以把主鍵改為shop_id 試試
ALTER TABLE `ouyangke`.`shop_goods`
CHANGE COLUMN `id` `shop_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT ' 商品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
設(shè)置模型對應(yīng)數(shù)據(jù)表字段及類型
默認會自動獲?。òㄗ侄晤愋停詣荧@取會導(dǎo)致增加一次查詢
schema 屬性一旦定義,就必須定義完整的數(shù)據(jù)表字段類型
類型根據(jù)php數(shù)據(jù)類型定義,如果是json類型直接定義為json即可
class Goods extends Model{
protected $name = 'Goods';
protected $table = 'shop_goods';
protected $pk = 'shop_id';
protected $schema = [
'shop_id' => 'int',
'cat' => 'int',
'title' => 'string',
'price' => 'float',
'discount' => 'int',
'stock' => 'int',
'status' => 'int',
'add_time' => 'int'
];
# 對某個字段定義需要自動轉(zhuǎn)換的類型,可以使用type屬性
protected $type = [
'shop_id' => 'int'
];
public function select(){
$select = Goods::select();
return $select->toArray();
}
}
4、disuse
數(shù)據(jù)表廢棄字段(數(shù)組)
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、其他屬性(不常用)
屬性 | 描述 |
suffix | 數(shù)據(jù)表后綴(默認為空) |
connection | 數(shù)據(jù)庫連接(默認讀取數(shù)據(jù)庫配置) |
query | 模型使用的查詢類名稱 |
field | 模型允許寫入的字段列表(數(shù)組) |
strict | 是否嚴格區(qū)分字段大小寫(默認為 true ) |
readonly | 字段只讀 |
json | 設(shè)置字段為JSON數(shù)據(jù) |
jsonType | 設(shè)置JSON字段的類型 |
jsonAssoc | 設(shè)置JSON數(shù)據(jù)返回數(shù)組 |
autoWriteTimestamp | 自動寫入創(chuàng)建和更新的時間戳字段(默認關(guān)閉) |
createTime | 創(chuàng)建時間戳字段 |
updateTime | 更新時間戳字段 |
deleteTime | 用于定義你的軟刪除標記字段 |
defaultSoftDelete | 定義軟刪除字段的默認值 |
四、模型 主要功能
1、獲取器
獲取器的作用是對模型實例的(原始)數(shù)據(jù)做出自動處理
命名規(guī)則:
get + 字段名 + Attr
字段名是數(shù)據(jù)表字段的駝峰轉(zhuǎn)換
class Goods extends Model{
public function index(){
$find = Goods::find(10);
echo $find->status;
return $find->toArray();
}
public function getStatusAttr($v){
$status = [
1=>'開啟',
2=>'關(guān)閉'
];
return $status[$v];
}
}
2、修改器
修改器的主要作用是對模型設(shè)置的數(shù)據(jù)對象值進行處理
命名規(guī)則:
set + 字段名 + Attr
class Goods extends Model{
public function index(){
$create = Goods::create([
'cat' => 3.33,
'title' => '新商品',
'price' => '59.99',
'add_time' => time()
]);
return $create;
}
public function setCatAttr($v,$all){
// $all 全部參數(shù)
return (int)$v;
}
}
3、搜索器
搜索器的作用是用于封裝字段(或者搜索標識)的查詢條件表達式
命名規(guī)則:
search + 字段名 + Attr
class Goods extends Model{
public function index(){
$select = Goods::withSearch(['title'],[
'title' => '新'
])->select();
return $select->toArray();
}
public function searchTitleAttr($query,$v){
$query->where('title','like', $v . '%');
}
}
4、檢查數(shù)據(jù)
如果要判斷數(shù)據(jù)集是否為空,不能直接使用
empty
判斷必須使用數(shù)據(jù)集對象的
isEmpty
方法判斷
class Goods extends Model{
public function index(){
$select = Goods::where('title','1')->select();
if(empty($select)){
echo 111;
}
if($select->isEmpty()){
echo 111;
}
}
}
五、右側(cè)列表改為model示例
model代碼
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();
$list = Goods::where($where)
->order($order)
->page($p,$total)
->select();
if($list->isEmpty()){
return null;
}
$data = $list->toArray();
foreach($data as &$data_v){
$data_v['cat'] = Db::table('shop_cat')->where('id',$data_v['cat'])->value('name');
}
$arr = [
'count' => ceil($count/$total),
'data' => $data
];
return $arr;
}
public function getStatusAttr($v){
$status = [
1=>'開啟',
2=>'關(guān)閉'
];
return $status[$v];
}
public function getAddTimeAttr($v){
return date('Y-m-d',$v);
}
}
controller代碼
public function index(){
$title = '商城';
$login = '歐陽克';
# 左側(cè)菜單
$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();
}
# 右側(cè)列表
$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>
六、模型事件
模型事件是指在進行模型的查詢和寫入操作的時候觸發(fā)的操作行為
模型事件只在調(diào)用模型的方法生效,使用查詢構(gòu)造器操作是無效的
編號 | 事件 | 描述 | 事件方法名 |
1 | after_read | 查詢后 | onAfterRead |
2 | before_insert | 新增前 | onBeforeInsert |
3 | after_insert | 新增后 | onAfterInsert |
4 | before_update | 更新前 | onBeforeUpdate |
5 | after_update | 更新后 | onAfterUpdate |
6 | before_write | 寫入前 | onBeforeWrite |
7 | after_write | 寫入后 | onAfterWrite |
8 | before_delete | 刪除前 | onBeforeDelete |
9 | after_delete | 刪除后 | onAfterDelete |
10 | before_restore | 恢復(fù)前 | onBeforeRestore |
11 | after_restore | 恢復(fù)后 | 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; } # 執(zhí)行更新操作,就會之下onBeforeUpdate方法 public static function onBeforeUpdate($goods){ print_r($goods->price); return true; } }