一對一關聯 hasOne
定義關聯
定義一對一關聯,例如,每個用戶都有一個個人資料信息,我們定義 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' // 關聯模型的數據表的主鍵
)]
public function profile()
{
return $this->relateOne();
}
}
關聯查詢
定義好關聯之后,就可以使用下面的方法獲取關聯數據:
<?php
$user = User::findRecord(1);
// 輸出 UserProfile 關聯模型的email屬性
echo $user->profile()->email;