模(mo)型(xing)對(dui)象(xiang)的關(guan)聯(lian)屬(shu)性(xing)可以(yi)直(zhi)接作(zuo)為當前(qian)模(mo)型(xing)對(dui)象(xiang)的動態屬(shu)性(xing)進(jin)行賦(fu)值或者取(qu)值操作(zuo)(延遲查詢),雖然該屬(shu)性(xing)并(bing)非數據表字(zi)段,例如(ru):

<?php
namespace app\index\model;

use think\Model;

class User extends Model
{
    public function profile()
    {
        return $this->hasOne('Profile');
    }
}

我們在使用

// 查詢(xun)模型(xing)數據
$user = User::find(1);
// 獲取動態屬性
dump($user->profile);
// 給關聯模(mo)型屬性賦值
$user->profile->phone = '1234567890';
// 保存關聯模型數據
$user->profile->save();

在獲取動態屬性profile的(de)同時,模型會(hui)通過定義的(de)關聯方(fang)法去查(cha)詢(xun)關聯對象的(de)數(shu)據(ju)并賦值給該動態(tai)屬性,這是一(yi)種關聯數(shu)據(ju)的(de)“惰性加載”,只有真(zhen)正訪問關聯屬性的(de)時候才會(hui)進行關聯查(cha)詢(xun)。

當有大量的關(guan)(guan)聯數據(ju)需要查詢(xun)的時候,一(yi)般都會考慮選(xuan)擇(ze)關(guan)(guan)聯預載(zai)入的方式(參(can)考下(xia)一(yi)節)。