之前學會了怎麼創建entity和數據庫的常用配置,現在來看看entity定義column時的常用類型以及一些屬性,這樣就可以完全掌控定義entity了。
使用@ORM\Column 定義字段
type:用來定義字段的類型
一些字段常用的type:
string:字符串類型,對應varchar integer:int類型 smallint:短int類型 bigint:長int類型 boolean:布爾類型 decimal:對應數據庫decmail類型,雙精度類型 datetime:日前datetime類型 time:time類型 text:文本類型 float:浮點類
name: 字段的名稱
length : 字段的長度
unique :字段在數據庫中的長度,只支持string類型使用
nullable : 數據庫是否爲空
options:條件組合
下面常見的有
default :字段默認值
unsigned : 非負數
comment : 字段說明註釋
example:
<?php /** * @ORM\var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string", length=32, unique=true, nullable=false) */ protected $username; /** * @ORM\Column(type="string", columnDefinition="CHAR(2) NOT NULL") */ protected $country; /** * @ORM\Column(type="decimal", precision=2, scale=1) */ protected $height; /** * @ORM\Column(type="string", length=2, options={"fixed":true, "comment":"Initial letters of first and last name"}) */ protected $initials; /** * @ORM\Column(type="integer", name="login_count" nullable=false, options={"unsigned":true, "default":0}) */ protected $loginCount;
使用@ORM\Entity指定repository
<?php /** * @ORM\Entity(repositoryClass="MyProject\UserRepository") */ classUser { //... }
使用@ORM\Table對錶重新定義
name : 定義表的名字
indexes : 定義一組索引
uniqueConstraints : 定義一組約束
<?php /** * @Entity * @Table(name="user", * uniqueConstraints={@UniqueConstraint(name="user_unique",columns={"username"})}, * indexes={@Index(name="user_idx", columns={"email"})} * ) */ classUser{}
使用@ORM\Index定義一個索引
<?php /** * @ORM\Entity * @ORM\Table(name="ecommerce_products",indexes={@ORM\Index(name="search_idx", columns={"name", "email"}, options={"where": "(((id IS NOT NULL) AND (name IS NULL)) AND (email IS NULL))"})}) */ classECommerceProduct { }
使用@ORM\HasLifecycleCallbacks 做事件回調
<?php /** * @ORM\Entity * @ORM\HasLifecycleCallbacks */ classUser { /** * @ORM\PostPersist */ publicfunctionsendOptinMail(){} }
可以使用@ORM\PostLoad, @ORM\PrePersist, @ORM\PostPersist, @ORM\PreRemove,
@ORM\PostRemove, @ORM\PreUpdate or @ORM\PostUpdate 當這些事件發生的時候,觸發一個回調。