項目示例使用MySQL數(shù)據(jù)庫
一、數(shù)據(jù)庫
1、修改項目設(shè)置
打開config\app.php修改配置

2、數(shù)據(jù)庫連接
- 數(shù)據(jù)準(zhǔn)備

- 全局配置
打開config\database.php修改配置

public function conn()
{
return Db::table('student')
->where('id','2')
->value('name');
}

- 動態(tài)配置
public function conn2()
{
return Db::connect([
'type'=>'mysql',
'hostname'=>'localhost',
'database'=>'demo',
'username'=>'root',
'password'=>'root',
])
->table('student')
->where('id','5')
->value('name');
}

- DSN連接
public function conn3()
{
$dsn = 'mysql://root:root@localhost/demo#utf8';
return Db::connect($dsn)
->table('student')
->where('id','3')
->value('name');
}

3、增刪改查操作
- 單條查詢
public function find()
{
/**
* Db類數(shù)據(jù)庫操作的入口類
* 功能:靜態(tài)調(diào)用think\db\Query.php類中的查詢方法實(shí)現(xiàn)基本操作
* table():選擇數(shù)據(jù)表
* field():用來設(shè)置返回的字段或別名
* where():設(shè)置查詢條件 表達(dá)式,數(shù)組
* 1、單個條件 使用表達(dá)式
* 2、對于多個條件使用數(shù)組
* find()返回符合條件的第一條記錄,沒有的話返回null
*/
// $res = Db::table('student')
// ->field('id,name,email')
// ->field(['id'=>'編號','name'=>'姓名','email'=>'郵箱'])
// ->where('id',4) //如果是相等關(guān)系 = 可忽略
// ->find();
// dump(is_null($res) ? '沒有找到' : $res);
$res = Db::table('student')
->field('id,name,email')
->find(5); //如果是主鍵查詢,可省略where()
dump(is_null($res) ? '沒有找到' : $res);
}

單條查詢原理

【問題】
//返回字段設(shè)置別名出錯,暫時還沒找到原因?
->field(['id'=>'編號','name'=>'姓名','email'=>'郵箱'])

-
多條查詢
public function select() { //select()返回的是一個二維數(shù)組,沒有數(shù)據(jù)返回是一個空數(shù)據(jù) $res = Db::table('student') ->field('id,name,email') ->where([ ['age','=',18], ['id','<=',5] ]) ->select(); if (empty($res)){ return '沒有滿足條件的記錄'; } else { foreach ($res as $row) { dump($row); } } }多條查詢原理
-
單條插入
public function insert() { //insert()成功返回新增的數(shù)量,失敗返回false //準(zhǔn)備一下要插入的數(shù)據(jù) $data = [ 'name'=>'金毛獅王4', 'age'=>52, 'email'=>'jinmaoshiwang2@163.com', ]; // return Db::table('student')->insert($data); //只有數(shù)據(jù)庫類型為MySQL的時候,才可以傳入true //REPLACE INTO方式插入,性能更高 // return Db::table('student')->insert($data,true); //data()方法對數(shù)據(jù)進(jìn)行過濾,更安全,insert不支持參數(shù)true // return Db::table('student')->data($data)->insert(); //插入的同時返回新增主鍵ID //insertGetId()同時執(zhí)行兩步:第一步插入,第二步返回主鍵ID return Db::table('student')->insertGetId($data); }insertGetId原理
-
多條插入
public function insertAll() { $data = [ ['name'=>'多條插入','age'=>1,'email'=>'duotiao@163.com'], ['name'=>'多條插入1','age'=>2,'email'=>'duotiao1@163.com'], ['name'=>'多條插入2','age'=>3,'email'=>'duotiao2@163.com'], ]; // return Db::table('student')->insertAll($data); return Db::table('student')->data($data)->insertAll(); }多條插入原理
-
更新操作
public function update() { //update()必須要有更新條件 // return Db::table('student') // ->where('id',2) // ->update(['name'=>'郭靖被修改了']); //如果更新條件是主鍵的話,可以直接把主鍵寫到更新數(shù)組中 return Db::table('student') ->update(['name'=>'郭靖被修改了','id'=>2]); }更新原理
-
刪除操作
public function delete() { // return Db::table('student') // ->delete(13); return Db::table('student') ->where('id',12) ->delete(); }刪除原理
-
原生查詢
public function query() { $sql = "SELECT `id`,`name`,`email` FROM `student` WHERE `id` IN (3,4,5)"; dump(Db::query($sql)); } -
原生寫操作:更新,刪除,添加
public function execute() { // return Db::execute("UPDATE `student` SET `name`='武松' WHERE `id`=10"); // return Db::execute("INSERT `student` SET `name`='宋江'"); return Db::execute("DELETE FROM `student` WHERE `name`='宋江'"); }
二、模型
1、模型定義
定義一個Student模型類很簡單:
<?php
namespace app\demo\model;
use think\model;
class Student extends model
{
}
請確保你已經(jīng)在數(shù)據(jù)庫配置文件中配置了數(shù)據(jù)庫連接信息
模型會自動對應(yīng)數(shù)據(jù)表,模型類的命名規(guī)則是除去表前綴的數(shù)據(jù)表名稱,采用駝峰法命名,并且首字母大寫,例如:
| 模型名稱 | 模型名 約定對應(yīng)數(shù)據(jù)表(假設(shè)數(shù)據(jù)庫的前綴定義是 think_) |
|---|---|
| User | think_user |
| UserType | think_user_type |
模型自動對應(yīng)的數(shù)據(jù)表名稱都是遵循小寫+下劃線規(guī)范,如果你的表名有大寫的情況,必須通過設(shè)置模型的table屬性。
如果擔(dān)心模型的名稱和PHP關(guān)鍵字沖突,可以啟用類后綴功能,只需要在應(yīng)用配置文件app.php中設(shè)置:
// 開啟應(yīng)用類庫后綴
'class_suffix' => true,
開啟后,所有的應(yīng)用類庫定義的時候都需要加上對應(yīng)后綴,包括控制器類。
這樣app\demo\model\Student類定義就要改成
<?php
namespace app\demo\model;
use think\Model;
class StudentModel extends Model
{
}
并且文件名也要改為StudentModel.php。
大多數(shù)情況下,不同模塊的模型是不需要獨(dú)立的,因此可以統(tǒng)一在
common模塊下面定義模型。
2、模型設(shè)置
默認(rèn)主鍵為id,如果你沒有使用id作為主鍵名,需要在模型中設(shè)置屬性:
<?php
namespace app\demo\model;
use think\Model;
class Student extends Model
{
protected $pk = 'sid';
}
5.1中模型不會自動獲取主鍵名稱,必須設(shè)置pk屬性。
如果你想指定數(shù)據(jù)表甚至數(shù)據(jù)庫連接的話,可以使用:
<?php
namespace app\ demo\model;
use think\Model;
class Student extends Model
{
// 設(shè)置當(dāng)前模型對應(yīng)的完整數(shù)據(jù)表名稱
protected $table = 'think_student';
// 設(shè)置當(dāng)前模型的數(shù)據(jù)庫連接
protected $connection = 'db_config';
}
connection屬性的建議用配置參數(shù)名(需要在database.php中添加)而不是具體的連接信息,從而避免把數(shù)據(jù)庫連接固化在代碼里面。
常用的模型設(shè)置屬性包括(以下屬性都不是必須設(shè)置):
| 屬性 | 描述 |
|---|---|
| name | 模型名(默認(rèn)為當(dāng)前不含后綴的模型類名) |
| table | 數(shù)據(jù)表名(默認(rèn)自動獲?。?/td> |
| pk | 主鍵名(默認(rèn)為id) |
| connection | 數(shù)據(jù)庫連接(默認(rèn)讀取數(shù)據(jù)庫配置) |
| query | 模型使用的查詢類名稱 |
| field | 模型對應(yīng)數(shù)據(jù)表的字段列表(數(shù)組 |
3、模型初始化
模型同樣支持初始化,與控制器的初始化不同的是,模型的初始化是定義Model的init方法,具體如下
<?php
namespace app\demo\model;
use think\Model;
class Student extends Model
{
// 模型初始化
protected static function init()
{
//TODO:初始化內(nèi)容
}
}
模型初始化方法通常用于注冊模型的事件操作。
init必須是靜態(tài)方法,并且只在第一次實(shí)例化的時候執(zhí)行
4、模型操作
在模型中除了可以調(diào)用數(shù)據(jù)庫類的方法之外(換句話說,數(shù)據(jù)庫的所有查詢方法模型中都可以支持),可以定義自己的方法,所以也可以把模型看成是數(shù)據(jù)庫的增強(qiáng)版。
模型的查詢方法無需和數(shù)據(jù)庫查詢一樣調(diào)用table或者name方法,因為模型會按照規(guī)則自動匹配對應(yīng)的數(shù)據(jù)表,例如:
Db::name('Student')->where('id','>',10)->select();
改成模型操作的話就變成
Student::where('id','>',10)->select();
雖然看起來是相同的查詢條件,但一個最明顯的區(qū)別是查詢結(jié)果的類型不同。
第一種方式的查詢結(jié)果是一個(二維)數(shù)組,而第二種方式的查詢結(jié)果是包含了模型(集合)的數(shù)據(jù)集。不過,在大多數(shù)情況下,這二種返回類型的使用方式并無明顯區(qū)別。
更多操作參考示例代碼
總結(jié)
這一章講了數(shù)據(jù)庫與模型技術(shù)相關(guān)操作,
-
數(shù)據(jù)庫介紹了配置連接的各種方式,CURD常規(guī)操作,示例代碼參考demo\controller\DataBase.php -
模型介紹了數(shù)據(jù)表的映射關(guān)系,方便數(shù)據(jù)操作,示例代碼參考demo\controller\Model.php
同時感謝PHP中文網(wǎng) 的教學(xué)資源...
以上均是自學(xué)過程的積累,學(xué)到哪記到哪
原創(chuàng)文章,轉(zhuǎn)載請注明出處,謝謝!










