我正在尝试将我的User实体设置为使用角色,并遵循http://symfony.com/doc/current/cookbook/security/entity_provider.html
用户工作得很好,如果我硬编码$roles值,一切都如预期,登录/注销就很好,等等。但是,如果我试图通过文档中概述的多对多关系检索角色,我会返回null。
我还应该提到,在创建实体后,当我运行"php-app/console原则:模式:更新-强制"时,它创建了角色表,但没有像它所说的那样创建"user_role"表。我手动创建了它,并为正在测试的用户输入了一行,但这是我第一次发现有些东西不起作用。这真的很令人沮丧,因为我遵循了文档,看起来它应该有效。
我在尝试登录时返回的错误是:
FatalErrorException: Error: Call to a member function toArray() on a non-object
它指向用户实体中的return $this->roles->toArray()
。
我的用户实体(相关位):
use Doctrine'ORM'Mapping as ORM;
use Symfony'Component'Security'Core'User'UserInterface;
/**
*
* @ORM'Table()
* @ORM'Entity(repositoryClass="ACME'MyBundle'Entity'UserRepository")
*
*/
class User implements UserInterface, 'Serializable
{
...
/**
* @ORM'ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
...
/**
* Constructor
*/
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getRoles()
{
return $this->roles->toArray();
}
...
}
我的角色实体:
use Symfony'Component'Security'Core'Role'RoleInterface;
use Doctrine'Common'Collections'ArrayCollection;
use Doctrine'ORM'Mapping as ORM;
/**
* @ORM'Table(name="role")
* @ORM'Entity()
*/
class Role implements RoleInterface
{
/**
* @ORM'Column(name="id", type="integer")
* @ORM'Id()
* @ORM'GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM'Column(name="name", type="string", length=30)
*/
private $name;
/**
* @ORM'Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* @ORM'ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* @see RoleInterface
*/
public function getRole()
{
return $this->role;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Role
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set role
*
* @param string $role
* @return Role
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
}
有人在我的代码中看到问题吗?或者有同样问题的经验吗?我现在被卡住了。
在您的实体角色中,您有
* @ORM'Table(name="role")
将其更改为
* @ORM'Table(name="user_role")
因为您的表名是user_role而不是角色
我遇到了同样的问题,我删除了toArray方法
use Doctrine'ORM'Mapping as ORM;
use Symfony'Component'Security'Core'User'UserInterface;
/**
*
* @ORM'Table()
* @ORM'Entity(repositoryClass="ACME'MyBundle'Entity'UserRepository")
*
*/
class User implements UserInterface, 'Serializable
{
...
/**
* @ORM'ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
...
/**
* Constructor
*/
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getRoles()
{
return $this->roles;//return $this->roles->toArray();
}
...
}