## 一對一關聯
定義一對一關聯,例如,一個用戶都有一個個人資料,我們定義User 模型如下:
~~~
namespace app\index\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile')->field('id,name,email');
}
}
~~~
**關聯查找**
定義好關聯之后,就可以使用下面的方法獲取關聯數據:
~~~
$user = User::find(1);
// 輸出Profile關聯模型的email屬性
echo $user->profile->email;
~~~
默認情況下, 我們使用的是user_id 作為外鍵關聯,如果不是的話則需要在關聯定義的時候指定,例如:
~~~
namespace app\index\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile','uid');
}
}
~~~
**關聯新增**
~~~
$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 模型中定義一個相對的關聯關系,例如:
~~~
namespace app\index\model;
use think\Model;
class Profile extends Model
{
public function user()
一對一關聯
本文檔使用 看云 構建 - 266 -
{
return $this->belongsTo('User');
}
}
~~~
belongsTo 的參數包括:
**belongsTo('關聯模型名','外鍵名','關聯表主鍵名',['模型別名定義'],'join類型');**
默認的關聯外鍵是user_id ,如果不是,需要在第二個參數定義
~~~
namespace app\index\model;
use think\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User','uid');
}
}
~~~
我們就可以根據檔案資料來獲取用戶模型的信息
~~~
$profile = Profile::find(1);
// 輸出User關聯模型的屬性
echo $profile->user->account;
~~~