Symfony2连接表以从另一个表获取列 [英] Symfony2 Join table to get column from another table
问题描述
我是MySQL和Doctrine的新手,
I'm kind of new to MySQL and Doctrine,
我基本上有两个表 User
和 Role
这样的表
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 |
+--------------------------------------+--------------------+
我遵循了Symfony网站上的教程,但是我真的不知道如何从用户实体中的角色获取 name
.
I followed the tutorial on Symfony's website, but I don't really know how to get name
from role in the User Entity.
当前它是这样写的:
老实说,我不知道它是否可以正确加入,任何帮助都会很棒
I honestly don't know if it is joining it correctly, any help would be awesome
推荐答案
除了使用ManyToMany关系外,我对用户和角色也有类似的设置.毕竟,我认为大多数应用程序都希望能够为用户分配多个角色.
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.
需要按如下所示设置关联.当然,您需要创建适当的getter/setter来为用户分配角色.
The associations need to be setup like the below. You'll need to create proper getter/setters for assigning roles to users, of course.
用户
/**
* @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();
}
角色
/**
* @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());
这篇关于Symfony2连接表以从另一个表获取列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!