`view`方法可以實現不依賴數據庫視圖的多表查詢,并不需要數據庫支持視圖,是`JOIN`方法的推薦替代方法,例如:
?
```
Db::view('User', 'id,name')
->view('Profile', 'truename,phone,email', 'Profile.user_id=User.id')
->view('Score', 'score', 'Score.user_id=Profile.id')
->where('score', '>', 80)
->select();
```
生成的SQL語句類似于:
```
SELECT User.id,User.name,Profile.truename,Profile.phone,Profile.email,Score.score FROM think_user User INNER JOIN think_profile Profile ON Profile.user_id=User.id INNER JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80
```
?
>[info] 注意,視圖查詢無需調用`table`和`join`方法,并且在調用`where`和`order`方法的時候只需要使用字段名而不需要加表名。
?
默認使用`INNER join`查詢,如果需要更改,可以使用:
```
Db::view('User', 'id,name')
->view('Profile', 'truename,phone,email', 'Profile.user_id=User.id', 'LEFT')
->view('Score', 'score', 'Score.user_id=Profile.id', 'RIGHT')
->where('score', '>', 80)
->select();
```
生成的SQL語句類似于:
```
SELECT User.id,User.name,Profile.truename,Profile.phone,Profile.email,Score.score FROM think_user User LEFT JOIN think_profile Profile ON Profile.user_id=User.id RIGHT JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80
```
?
可以使用別名:
```
Db::view('User', ['id' => 'uid', 'name' => 'account'])
->view('Profile', 'truename,phone,email', 'Profile.user_id=User.id')
->view('Score', 'score', 'Score.user_id=Profile.id')
->where('score', '>', 80)
->select();
```
?
生成的SQL語句變成:
```
SELECT User.id AS uid,User.name AS account,Profile.truename,Profile.phone,Profile.email,Score.score FROM think_user User INNER JOIN think_profile Profile ON Profile.user_id=User.id INNER JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80
```
?
可以使用數組的方式定義表名以及別名,例如:
```
Db::view(['think_user' => 'member'], ['id' => 'uid', 'name' => 'account'])
->view('Profile', 'truename,phone,email', 'Profile.user_id=member.id')
->view('Score', 'score', 'Score.user_id=Profile.id')
->where('score', '>', 80)
->select();
```
?
生成的SQL語句變成:
```
SELECT member.id AS uid,member.name AS account,Profile.truename,Profile.phone,Profile.email,Score.score FROM think_user member INNER JOIN think_profile Profile ON Profile.user_id=member.id INNER JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80
```
- 簡介
- 數據庫配置
- 分布式數據庫
- 查詢構造器
- 查詢數據
- 新增數據
- 更新數據
- 刪除數據
- 鏈式操作
- Where
- Table
- Alias
- Field
- Strict
- Limit
- Page
- Order
- Group
- Having
- Join
- Union
- Distinct
- Lock
- Cache
- Comment
- FetchSql
- Force
- Partition
- Replace
- FailException
- Extra
- Duplicate
- Sequence
- Procedure
- View
- 聚合查詢
- 分頁查詢
- 時間查詢
- 高級查詢
- 子查詢
- 原生查詢
- 事務操作
- 存儲過程
- 查詢事件
- JSON字段
- 模型
- 定義
- 新增
- 更新
- 刪除
- 查詢
- 查詢范圍
- 只讀字段
- JSON字段
- 自動時間寫入
- 獲取器
- 修改器
- 搜索器
- 類型轉換
- 模型輸出
- 模型事件
- 虛擬模型
- 關聯
- 一對一關聯
- 一對多關聯
- 遠程一對多
- 遠程一對一
- 多對多關聯
- 多態一對多
- 多態一對一
- 關聯預載入
- 關聯統計
- 關聯輸出
- SQL監聽
- 緩存機制
- 字段緩存
- 查詢緩存
- 擴展
- 自定義查詢類
- 自定義數據庫驅動