一對(duì)一關(guān)聯(lián) hasOne
定義關(guān)聯(lián)
定義一對(duì)一關(guān)聯(lián),例如,每個(gè)用戶都有一個(gè)個(gè)人資料信息,我們定義 User
模型如下:
<?php
declare(strict_types=1);
namespace EasySwoole\FastDb\Tests\Model;
use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;
use EasySwoole\FastDb\Attributes\Relate;
use EasySwoole\FastDb\Tests\Model\UserProfile;
/**
* @property int $id
* @property string $name
* @property string $email
*/
class User extends AbstractEntity
{
#[Property(isPrimaryKey: true)]
public int $id;
#[Property]
public ?string $name;
#[Property]
public ?string $email;
public function tableName(): string
{
return 'easyswoole_user';
}
#[Relate(
targetEntity: UserProfile::class,
targetProperty: 'user_id' // 關(guān)聯(lián)模型的數(shù)據(jù)表的主鍵
)]
public function profile()
{
return $this->relateOne();
}
}
關(guān)聯(lián)查詢
定義好關(guān)聯(lián)之后,就可以使用下面的方法獲取關(guān)聯(lián)數(shù)據(jù):
<?php
$user = User::findRecord(1);
// 輸出 UserProfile 關(guān)聯(lián)模型的email屬性
echo $user->profile()->email;