一對一關聯的場景比較常見,比如每個用戶都有一個身份證,每個國家都有一個首都,這種關聯我們稱為`HasOne`關聯。通常一對一關聯的反向關聯也是一對一關系,比如一個身份證屬于一個用戶,一個首都屬于一個國家,這種反向一對一關聯我們成為`BelongsTo`關聯。
## 關聯定義
定義一對一關聯,例如,一個用戶都有一個個人資料,我們定義`User`模型如下:
~~~
<?php
namespace app\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
~~~
`hasOne`方法的參數包括:
>[info] ### hasOne('關聯模型類名', '外鍵', '主鍵');
除了關聯模型外,其它參數都是可選。
* **關聯模型**(必須):關聯模型類名
* **外鍵**:默認的外鍵規則是當前模型名(不含命名空間,下同)+`_id` ,例如`user_id`
* **主鍵**:當前模型主鍵,默認會自動獲取也可以指定傳入
一對一關聯定義的時候還支持額外的方法,包括:
方法名|描述
---|---
bind|綁定關聯屬性到父模型
joinType|JOIN方式查詢的JOIN方式,默認為`INNER`
>[danger] 如果使用了JOIN方式的關聯查詢方式,你可以在額外的查詢條件中使用關聯對象名(不含命名空間)作為表的別名。
## 關聯查詢
定義好關聯之后,就可以使用下面的方法獲取關聯數據:
~~~
$user = User::find(1);
// 輸出Profile關聯模型的email屬性
echo $user->profile->email;
~~~
默認情況下, 我們使用的是`user_id` 作為外鍵關聯,如果不是的話則需要在關聯定義的時候指定,例如:
~~~
<?php
namespace app\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class, 'uid');
}
}
~~~
>[danger] 有一點需要注意的是,關聯方法的命名規范是駝峰法,而關聯屬性則一般是小寫+下劃線的方式,系統在獲取的時候會自動轉換對應,讀取`user_profile`關聯屬性則對應的關聯方法應該是`userProfile`。
### 根據關聯數據查詢
可以根據關聯條件來查詢當前模型對象數據,例如:
~~~
// 查詢用戶昵稱是think的用戶
// 注意第一個參數是關聯方法名(不是關聯模型名)
$users = User::hasWhere('profile', ['nickname'=>'think'])->select();
// 可以使用閉包查詢
$users = User::hasWhere('profile', function($query) {
$query->where('nickname', 'like', 'think%');
})->select();
~~~
### 預載入查詢
可以使用預載入查詢解決典型的`N+1`查詢問題,使用:
~~~
$users = User::with('profile')->select();
foreach ($users as $user) {
echo $user->profile->name;
}
~~~
上面的代碼使用的是`IN`查詢,只會產生2條SQL查詢。
如果要對關聯模型進行約束,可以使用閉包的方式。
~~~
$users = User::with(['profile' => function($query) {
$query->field('id,user_id,name,email');
}])->select();
foreach ($users as $user) {
echo $user->profile->name;
}
~~~
`with`方法可以傳入數組,表示同時對多個關聯模型(支持不同的關聯類型)進行預載入查詢。
~~~
$users = User::with(['profile','book'])->select();
foreach ($users as $user) {
echo $user->profile->name;
foreach($user->book as $book) {
echo $book->name;
}
}
~~~
一對一關聯預載入查詢默認使用`IN`查詢,如果需要使用`JOIN`方式的查詢,使用`withJoin`方法,例如:
~~~
$users = User::withJoin('profile')->select();
foreach ($users as $user) {
echo $user->profile->name;
}
~~~
`withJoin`方法默認使用的是`INNER JOIN`方式,如果需要使用其它的,可以改成
~~~
$users = User::withJoin('profile', 'LEFT')->select();
foreach ($users as $user) {
echo $user->profile->name;
}
~~~
需要注意的是`withJoin`方式不支持嵌套關聯,通常你可以直接傳入多個需要關聯的模型。
如果需要約束關聯字段,必須在閉包中使用`withField`方法(`field`方法無效)
```
$users = User::withJoin(['profile' => function($query) {
$query->withField(['user_id', 'name', 'email']);
}])->select();
```
如果僅僅需要約束關聯字段,可以使用下面的簡便方法。
~~~
$users = User::withJoin([
'profile' => ['user_id', 'name', 'email']
])->select();
~~~
>[danger] 該用法僅限于`withJoin`方法。
## 關聯保存
~~~
$user = User::find(1);
// 如果還沒有關聯數據 則進行新增
$user->profile()->save(['email' => 'thinkphp']);
~~~
系統會自動把當前模型的主鍵傳入`Profile`模型。
和新增一樣使用`save`方法進行更新關聯數據。
~~~
$user = User::find(1);
$user->profile->email = 'thinkphp';
$user->profile->save();
// 或者
$user->profile->save(['email' => 'thinkphp']);
~~~
## 相對關聯
我們可以在`Profile`模型中定義一個相對的關聯關系,例如:
~~~
<?php
namespace app\model;
use think\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
~~~
`belongsTo`的參數包括:
>[info] ### belongsTo('關聯模型','外鍵', '關聯主鍵');
除了關聯模型外,其它參數都是可選。
* **關聯模型**(必須):關聯模型類名
* **外鍵**:當前模型外鍵,默認的外鍵名規則是關聯模型名+`_id`
* **關聯主鍵**:關聯模型主鍵,一般會自動獲取也可以指定傳入
默認的關聯外鍵是`user_id`,如果不是,需要在第二個參數定義
~~~
<?php
namespace app\model;
use think\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class, 'uid');
}
}
~~~
我們就可以根據檔案資料來獲取用戶模型的信息
~~~
$profile = Profile::find(1);
// 輸出User關聯模型的屬性
echo $profile->user->account;
~~~
## 綁定屬性到父模型
可以在定義關聯的時候使用`bind`方法綁定屬性到父模型,例如:
~~~
<?php
namespace app\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class, 'uid')->bind(['nickname', 'email']);
}
}
~~~
或者指定綁定屬性別名
~~~
<?php
namespace app\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class, 'uid')->bind([
'email',
'truename' => 'nickname',
]);
}
}
~~~
然后使用關聯預載入查詢的時候,可以使用
~~~
$user = User::with('profile')->find(1);
// 直接輸出Profile關聯模型的綁定屬性
echo $user->email;
echo $user->truename;
~~~
綁定關聯模型的屬性支持讀取器。
> 如果不是預載入查詢,請使用模型的`appendRelationAttr`方法追加屬性。
也可以使用動態綁定關聯屬性,可以使用
~~~
$user = User::find(1)->bindAttr('profile',['email','nickname']);
// 輸出Profile關聯模型的email屬性
echo $user->email;
echo $user->nickname;
~~~
同樣支持指定屬性別名
~~~
$user = User::find(1)->bindAttr('profile',[
'email',
'truename' => 'nickname',
]);
// 輸出Profile關聯模型的email屬性
echo $user->email;
echo $user->truename;
~~~
## 關聯自動寫入
我們可以使用`together`方法更方便的進行關聯自動寫入操作。
寫入
~~~php
$blog = new Blog;
$blog->name = 'thinkphp';
$blog->title = 'ThinkPHP5關聯實例';
$content = new Content;
$content->data = '實例內容';
$blog->content = $content;
$blog->together(['content'])->save();
~~~
如果綁定了子模型的屬性到當前模型,可以指定子模型的屬性
~~~php
$blog = new Blog;
$blog->name = 'thinkphp';
$blog->title = 'ThinkPHP5關聯實例';
$blog->content = '實例內容';
// title和content是子模型的屬性
$blog->together(['content'=>['title','content']])->save();
~~~
更新
~~~php
// 查詢
$blog = Blog::find(1);
$blog->title = '更改標題';
$blog->content->data = '更新內容';
// 更新當前模型及關聯模型
$blog->together(['content'])->save();
~~~
刪除
~~~
// 查詢
$blog = Blog::with('content')->find(1);
// 刪除當前及關聯模型
$blog->together(['content'])->delete();
~~~
- 簡介
- 數據庫配置
- 分布式數據庫
- 查詢構造器
- 查詢數據
- 新增數據
- 更新數據
- 刪除數據
- 鏈式操作
- 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監聽
- 緩存機制
- 字段緩存
- 查詢緩存
- 擴展
- 自定義查詢類
- 自定義數據庫驅動