Doctrine ODM MongoDB - Replicate Simple Links to Many Restricted Links

I am new to Doctrine, mongo, and the ODM setting, and while playing with this setting in ZF1, I am trying to replicate a simple link to a restricted link. This is the situation and I would like to advise how to achieve this.

This is a simple mapping of the user role and>, so in a SQL situation, I would have the following tables:

Users
 - id
 - name
 - role_id

Roles
 - id
 - name

Then the role_id user will be set to a foreign key constraint for matching the role identifier. And when the role is deleted, the foreign key restriction that stops the operation will be violated.

How could I achieve the same goal in Doctrines MongoDB ODM?

So far, I have played with various types of annotations on a User object, including @ReferenceOne @ReferenceMany with various cascade options ...

Now I can only implement the events @PreUpdate, @PreRemove of the life cycle in the "role" entity, and then check that none of the users use this role, if they are later updated, change the link to match or delete the exception.

Am I right here or lost?

Thank,

Si

+5
source share
1 answer

For something like this, I would not have two separate “tables”, as in SQL. You will simply have the role type as a user property. And then, if you want to remove the role type, you can simply manipulate the role fields of all users with this role.

, .

<?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();
        }
    }
}
+7

All Articles