![](/img/trans.png)
[英]Unidirectional many-to-one relation in Doctrine MongoDB ODM without MongoId
[英]Doctrine ODM MongoDB - Replicate a simple One to Many Reference with Constraint
我是Doctrine,mongo和ODM設置的新手,在ZF1中使用這個設置時,我試圖用約束復制一個簡單的一個到多個引用。 這是情況,並希望就如何實現這一點提出一些建議。
這是一個簡單的用戶 - >角色映射,所以在sql情況下我會有如下表:
Users - id - name - role_id Roles - id - name
然后,將在用戶role_id上設置外鍵約束以映射到角色ID。 刪除角色后,將觸發外鍵約束,停止操作。
我怎樣才能在Doctrines MongoDB ODM中實現相同的目標?
到目前為止,我在User實體上使用了不同類型的注釋,包括帶有不同級聯選項的@ReferenceOne @ReferenceMany ...
現在留給我的選擇是在'role'實體上實現@PreUpdate,@ PreRemove生命周期事件,然后檢查沒有用戶正在使用該角色,如果它們在更新時更改了引用以匹配或者在刪除時拋出異常。
我在這里還是迷路了?
謝謝,
硅
對於類似的東西,我不會像在SQL中那樣有兩個單獨的“表”。 您只需將角色類型作為用戶的屬性即可。 然后,如果要刪除角色類型,您只需操作具有該角色的所有用戶的角色字段即可。
但要回答你的問題,我會這樣做。
<?php
class User {
/** @MongoDB\Id */
protected $id;
/** @MongoDB\String */
protected $name;
/** @MongoDB\ReferenceOne(targetDocument="Role", mappedBy="user") */
protected $role;
//Getters/Setters
}
class Role {
/** @MongoDB\Id */
protected $id;
/** @MongoDB\String */
protected $name;
/** @MongoDB\ReferenceMany(targetDocument="User", inversedBy="role") */
protected $users;
public function _construct() {
$this->users = new Doctrine\Common\Collections\ArrayCollection;
}
// Getters/Setters
public function hasUsers() {
return !$this->users->isEmpty();
}
}
然后我將創建一個服務類來與我的文檔管理器一起工作。
class RoleService {
public function deleteRole(Role $role) {
if (!$role->hasUsers()) {
// Setup the documentManager either in a base class or the init method. Or if your über fancy and have php 5.4, a trait.
$this->documentManager->remove($role);
// I wouldn't always do this in the service classes as you can't chain
// calls without a performance hit.
$this->documentManager->flush();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.