Model
定義模型
模型定義規范
-
任何模型都必須繼承
\EasySwoole\FastDb\AbstractInterface\AbstractEntity
并實現tableName()
方法,該方法用于返回該數據表的表名。 -
任何模型都必須具有一個唯一主鍵,作為某個模型對象的唯一id,一般建議為
int
類型的自增id。 -
對象的屬性,也就是數據表對應的字段,請用
#[Property]
進行標記。
示例
例如,我們有個表名為 user
的數據表,表結構如下:
CREATE TABLE `easyswoole_user`
(
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'increment id',
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'name',
`status` tinyint unsigned DEFAULT '0' COMMENT 'status',
`score` int unsigned DEFAULT '0' COMMENT 'score',
`sex` tinyint unsigned DEFAULT '0' COMMENT 'sex',
`address` json DEFAULT NULL COMMENT 'address',
`email` varchar(150) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'email',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
則它對應的實體類如下:
<?php
declare(strict_types=1);
namespace App\Model;
use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;
/**
* @property int $id increment id
* @property string|null $name name
* @property int|null $status status
* @property int|null $score score
* @property int|null $sex sex
* @property string|null $address address
* @property string|null $email email
*/
class EasySwooleUser extends AbstractEntity
{
#[Property(isPrimaryKey: true)]
public int $id;
#[Property]
public ?string $name;
#[Property]
public ?int $status;
#[Property]
public ?int $score;
#[Property]
public ?int $sex;
#[Property]
public ?string $address;
#[Property]
public ?string $email;
public function tableName(): string
{
return 'easyswoole_user';
}
}