一對(duì)多關(guān)聯(lián) hasMany
定義關(guān)聯(lián)
<?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\UserCar;
/**
* @property int $id
* @property string $name
* @property int $status
* @property int $score
* @property string $email
*/
class User extends AbstractEntity
{
#[Property(isPrimaryKey: true)]
public int $id;
#[Property]
public ?string $name;
#[Property]
public ?int $status;
#[Property]
public ?int $score;
#[Property]
public ?int $create_time;
#[Property]
public ?string $info;
#[Property]
public ?string $foo;
#[Property]
public ?string $bar;
#[Property]
public ?int $login_time;
#[Property]
public ?int $login_times;
#[Property]
public ?int $read;
#[Property]
public ?string $title;
#[Property]
public ?string $content;
#[Property]
public ?string $email;
public function tableName(): string
{
return 'easyswoole_user';
}
#[Relate(
targetEntity: UserCar::class,
targetProperty: 'user_id'
)]
public function cars()
{
return $this->relateMany();
}
}
關(guān)聯(lián)查詢
<?php
$article = User::findRecord(1);
// 獲取用戶擁有的所有車輛品牌
$listResult = $article->cars();
foreach ($listResult as $userCar) {
echo $userCar->car_name . "\n";
}
// or
$objectArr = $listResult->toArray(); // 轉(zhuǎn)換為 對(duì)象數(shù)組
foreach ($objectArr as $userCar) {
echo $userCar->car_name . "\n";
}