clifford.duke
clifford.duke

Reputation: 4030

Symfony2 Join table to get column from another table

I'm kind of new to MySQL and Doctrine,

I basically have two tables User and Role that goes something like this

+--------------------------------------+--------------------+
|User                                  |   Role             |
|id    username    password    role    |   id    name       |
|1     testuser    something   1       |   1     ROLE_USER  |
+--------------------------------------+--------------------+

I followed the tutorial on Symfony's website, but I don't really know how to get name from role in the User Entity.

Currently it is written like so:

Role Entity

User Entity Snippet

I honestly don't know if it is joining it correctly, any help would be awesome

Upvotes: 1

Views: 3500

Answers (2)

lifo
lifo

Reputation: 2893

I have a similar setup with Users and Roles except I use a ManyToMany relationship. After all, I think most applications will want to be able to assign more than 1 role to a user.

The associations need to be setup like the below. You'll need to create proper getter/setters for assigning roles to users, of course.

User

/**
 * @ORM\ManyToMany(targetEntity="Role", cascade={"persist"})
 * @ORM\JoinTable(name="user_roles",
 *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id", onDelete="CASCADE")}
 * )
 */
protected $roles;

public function __construct() {
    $this->roles = new ArrayCollection();
}

Role

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
 */
protected $users;

public function __construct() {
    $this->users = new ArrayCollection();
}

The above would allow you use the roles like this:

$user = $this->getDoctrine()->getRepository('YourBundle:User')->find($id);
print_r($user->getRoles()->toArray());

Upvotes: 1

Ziumin
Ziumin

Reputation: 4860

You have to read doctrine documentation. There is description of OneToMany relationship mapping.

So Role entity should contain only $id and $name field mappings, but User entity $role field should look like

/**
 * @ManyToOne(targetEntity="Role")
 * @JoinColumn(name="role", referencedColumnName="id")
 **/
private $role;

Upvotes: 1

Related Questions