> ### 定義一對一關聯
> 描述:一個用戶有一份資料
> ## hasOne('關聯的模型', '外鍵名', '主鍵名', 'join類型')
> 有一點需要注意的是,關聯方法的命名規范是駝峰法,而關聯屬性則一般是小寫+下劃線的方式,系統在獲取的時候會自動轉換對應,讀取user_profile關聯屬性則對應的關聯方法應該是userProfile。
```
// 模型中這樣定義
class User extends Model
{
// 一個User有一個Profile
public function profile()
{
// 定義關聯(默認使用user_id作為外鍵進行關聯)
return $this->hasOne('Profile');
// 如果外鍵為uid,則需要如此設置
return $this->hasOne('Profile','uid');
// 指定關聯的字段
// 如果使用的是join方式的關聯,不支持指定field字段
return $this->hasOne('Profile')->field('id,name,email');
// 綁定指定的字段到父模型(支持讀取器)
return $this->hasOne('Profile','uid')->bind('nickname,email');
// 還可以給綁定到父模型的子模型字段指定別名
return $this->hasOne('Profile','uid')->bind([
'email',
'truename' => 'nickname',
'profile_id' => 'id',
]);
// 這樣可以直接在控制器這樣訪問
$user = User::get(1,'profile');
// 輸出Profile關聯模型的email屬性
echo $user->email;
echo $user->profile_id;
}
}
```
> ### 關聯查找
```
// 獲取關聯的屬性
$user = User::get(1);
echo $user->profile->email;
// 獲取指定條件的關聯屬性
$user = User::hasWhere('profile',['email'=>'thinkphp@qq.com'])->find();
echo $user->name;
```
> ### 關聯新增
```
$user = User::get(1);
// 如果還沒有關聯數據 則進行新增
$user->profile()->save(['email' => 'thinkphp']);
// 動態新增屬性
$user = User::find(1);
$user->profile->phone = '1234567890';
$user->profile->save();
```
> ### 關聯更新
```
$$user = User::get(1);
$user->profile->email = 'thinkphp';
$user->profile->save();
// 或者
$user->profile->save(['email' => 'thinkphp']);
```
> ## 定義反向關聯
> ### belongsTo('關聯模型名','外鍵名','關聯表主鍵名',['模型別名定義'],'join類型');
```
// Profile屬于User
class Profile extends Model
{
public function user()
{
// 默認關聯的外鍵為user_id
return $this->belongsTo('User');
// 如果需要指定關聯的外鍵
return $this->belongsTo('User','uid');
}
}
// 根據子模型獲取父模型的數據
profile = Profile::get(1);
// 輸出User關聯模型的屬性
echo $profile->user->account;
```
> ### 關聯自動寫入更新和刪除
```
// 關聯插入
$blog = new Blog;
$blog->name = 'thinkphp';
$content = new Content;
$content->data = '實例內容';
$blog->content = $content;
$blog->together('content')->save();
// 關聯更新(同時更新當前模型與其關聯模型)
$blog = Blog::get(1);
$blog->title = '更改標題';
$blog->content->data = '更新內容';
$blog->together('content')->save();
// 關聯刪除
$blog = Blog::get(1);
$blog->together('content')->delete();
```
- 運行環境需求
- tp5目錄結構
- 命令行生成代碼
- 路由
- 請求
- 獲取請求信息
- 超全局變量獲取
- 更改請求變量的值
- 判斷是否為某種請求類型
- 偽裝表單請求類型
- HTTP頭部信息
- 偽靜態
- 向請求對象中注入自定義的屬性和方法
- 簡單的傳參可以使用參數綁定
- 依賴注入(將對象注入方法作為參數)
- 將請求的數據進行緩存
- 控制器
- 一個控制器代碼示例
- 空控制器
- 資源控制器
- 模型
- 一個模型代碼示例
- 模型的四種調用方法
- 控制器中調用模型添加數據
- 控制器中調用模型更新數據
- 控制器中調用模型刪除數據
- 控制器中調用模型查詢數據
- 模型中使用聚合函數
- 獲取器
- 修改器
- 自動寫入時間戳
- 只讀字段
- 軟刪除
- 自動類型轉換
- 數據自動完成
- 查詢范圍
- 數組方式訪問和轉換為數組
- json序列化
- 模型的事件
- 關聯模型
- 一對一關聯
- 一對多關聯
- 遠程一對多(跨表關聯)
- 多對多關聯
- 多態關聯
- 關聯預載入N+1次查詢變2次
- 延遲預載入
- 關聯統計
- 視圖與模板
- 模板引擎配置
- 分配數據到模板
- 輸出替換
- 模板中輸出變量
- 模板中輸出系統變量(配置常量超全局)
- 模板中輸出請求信息
- 模板中使用php函數
- 輸出到模板中的變量指定默認值
- 模板中進行運算
- 原樣輸出代碼不解析
- 模版中注釋
- 模板布局與繼承
- 文件包含
- 內置標簽
- 循環輸出標簽
- 比較標簽
- 條件判斷標簽
- 引入資源文件(js-css)
- 使用原生php
- 在模板中定義變量和常量
- 助手函數
- 常用功能
- 表單驗證
- 驗證器的定義
- 自定義驗證規則
- 速查表
- 系統默認根命名空間
- 系統路徑常量
- 請求變量
- URL請求和信息方法