靠近'角色= ROLE_US':错误:'角色'没有定义。

时间:2015-02-24 12:09:31

标签: symfony doctrine-orm

我收到此错误

 "near 'role=ROLE_US': Error: 'role' is not defined"

我想添加一个新用户。我在sql查询中键入ROLE_USER,但stil得到此错误

对不起我的英文,谢谢你的帮助

defaultController.php

namespace Inz\RegisterBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Inz\RegisterBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Inz\RegisterBundle\Entity\Group;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use Doctrine\Common\Collections\ArrayCollection;

class DefaultController extends Controller
{
  /**
     * @Route("/register", name="register")
     * @Template()
     */
     public function registerAction(Request $request)
    {

    $user = new User();
     $group=new Group();
  $form = $this->createFormBuilder($user)
        ->add('username', 'text')
        ->add('password', 'text')
        ->add('email', 'email')
        ->add('submit','submit')
        ->getForm();

         $form->handleRequest($request);
 if ($form->isValid()) {
 $em = $this->getDoctrine()->getManager();
   $factory = $this->get('security.encoder_factory');
   $encoder = $factory->getEncoder($user);
   $user->setSalt(md5(time()));
   $pass =   $encoder->encodePassword($form->getData()->getPassword(),          $user->getSalt());
   $user->setPassword($pass);
 $group = $em->getRepository('InzRegisterBundle:Group')->findOneByRole(array('role' =>'ROLE_USER'));

   $user->addGroup($group);   
   $em->persist($group);
   $em->persist($user);
   $em->flush();

    return $this->redirect($this->generateUrl('login'));
}

    return $this->render('InzRegisterBundle:Default:register.html.twig', array(
        'form' => $form->createView(),
    ));
}

}

user.php的

    <?php
// src/Acme/UserBundle/Entity/User.php

namespace Inz\RegisterBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;


use Doctrine\ORM\Mapping as ORM;

  /**
 * Acme\UserBundle\Entity\User
 *
 * @ORM\Table(name="User")
 * @ORM\Entity(repositoryClass="Inz\RegisterBundle\Entity   \UserRepository")
 */
class User implements AdvancedUserInterface 
{
/**
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id()
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(name="username", type="string", length=25, unique=true)
 */
private $username;

/**
 * @ORM\Column(name="salt", type="string", length=40)
 */
private $salt;

/**
 * @ORM\Column(name="password", type="string", length=40)
 */
private $password;

/**
 * @ORM\Column(name="email", type="string", length=60, unique=true)
 */
private $email;

/**
 * @ORM\Column(name="isActive", type="boolean")
 */
private $isActive;

/**
 * @ORM\ManyToMany(targetEntity="Group", inversedBy="users")
 *
 */
private $groups;



public function __construct()
{
    $this->isActive = true;
    $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
    $this->groups = new ArrayCollection();

}

/**
 * @inheritDoc
 */
public function getRoles()
{
  $roles = array();
foreach ($this->groups as $role) {
    $roles[] = $role->getRole();
}
    return $roles;

}


public function eraseCredentials()
{
}

public function getUsername()
{
    return $this->username;
}

public function getSalt()
{
    return $this->salt;
}

public function getPassword()
{
    return $this->password;
}
  public function isAccountNonExpired()
{
    return true;
}

public function isAccountNonLocked()
{
    return true;
}

public function isCredentialsNonExpired()
{
    return true;
}

public function isEnabled()
{
    return $this->isActive;
}


/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set username
 *
 * @param string $username
 * @return User
 */
public function setUsername($username)
{
    $this->username = $username;

    return $this;
}

/**
 * Set salt
 *
 * @param string $salt
 * @return User
 */
public function setSalt($salt)
{
    $this->salt = $salt;

    return $this;
}

/**
 * Set password
 *
 * @param string $password
 * @return User
 */
public function setPassword($password)
{
    $this->password = $password;

    return $this;
}

/**
 * Set email
 *
 * @param string $email
 * @return User
 */
public function setEmail($email)
{
    $this->email = $email;

    return $this;
}

/**
 * Get email
 *
 * @return string 
 */
public function getEmail()
{
    return $this->email;
}

/**
 * Set isActive
 *
 * @param boolean $isActive
 * @return User
 */
public function setIsActive($isActive)
{
    $this->isActive = $isActive;

    return $this;
}

/**
 * Get isActive
 *
 * @return boolean 
 */
public function getIsActive()
{
    return $this->isActive;
}

/**
 * Add groups
 *
 * @param \Acme\UserBundle\Entity\Group $groups
 * @return User
 */
public function addGroup(\Acme\UserBundle\Entity\Group $groups)
{
    $groups->addUser($this);
    $this->groups -> add($groups);

    return $this->groups;
}

/**
 * Remove groups
 *
 * @param \Acme\UserBundle\Entity\Group $groups
 */
public function removeGroup(\Acme\UserBundle\Entity\Group $groups)
{
    $this->groups->removeElement($groups);
}

/**
 * Get groups
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getGroups()
{
    return $this->groups;
}

/**
 * Set research
 *
 * @param \Acme\UserBundle\Entity\Research $research
 * @return User
 */

}

group.php

<?php
namespace Inz\RegisterBundle\Entity;

use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;

use Doctrine\ORM\Mapping as ORM;

 /**
 * @ORM\Table(name="groups")
 * @ORM\Entity(repositoryClass="Inz\RegisterBundle\Entity\GroupRepository")
 */
 class Group implements RoleInterface, \Serializable
{
/**
 * @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="groups",cascade={"persist"}) */
private $users;

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

// ... getters and setters for each property

/** @see RoleInterface */
public function getRole()
{
    return $this->role;
}

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}


/**
 * @see \Serializable::serialize()
 */
public function serialize()
{
    /*
     * ! Don't serialize $users field !
     */
    return \json_encode(array(
        $this->id,
        $this->role
    ));
}

/**
 * @see \Serializable::unserialize()
 */
public function unserialize($serialized)
{
    list(
        $this->id,
        $this->role
    ) = \json_decode($serialized);
}

/**
 * Set name
 *
 * @param string $name
 * @return Group
 */
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 Group
 */
public function setRole($role)
{
    $this->role = $role;

    return $this;
}

/**
 * Add users
 *
 * @param \Acme\UserBundle\Entity\User $users
 * @return Group
 */
public function addUser(\Acme\UserBundle\Entity\User $users)
{
    $this->users[] = $users;

    return $this;
}

/**
 * Remove users
 *
 * @param \Acme\UserBundle\Entity\User $users
 */
public function removeUser(\Acme\UserBundle\Entity\User $users)
{
    $this->users->removeElement($users);
}

/**
 * Get users
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getUsers()
{
    return $this->users;
}
}

groupRepository.php

<?php
// src/Acme/UserBundle/Entity/UserRepository.php

namespace Inz\RegisterBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

class GroupRepository extends EntityRepository 
{
public function findOneByRole($role)
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM InzRegisterBundle:Group p WHERE role=ROLE_USER'
)
->getResult();
}
}

userRepository.php

<?php
// src/Acme/UserBundle/Entity/UserRepository.php

namespace Inz\RegisterBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

class UserRepository extends EntityRepository implements    UserProviderInterface
{
public function loadUserByUsername($username)
{
     $q = $this
        ->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.groups', 'g')
        ->where('u.username = :username OR u.email = :email')
        ->setParameter('username', $username)
        ->setParameter('email', $username)
        ->getQuery()
    ;

    try {
        // The Query::getSingleResult() method throws an exception
        // if there is no record matching the criteria.
        $user = $q->getSingleResult();
    } catch (NoResultException $e) {
        throw new UsernameNotFoundException(sprintf('Unable to find an active admin AcmeUserBundle:User object identified by "%s".', $username), null, 0, $e);
    }

    return $user;
}

public function refreshUser(UserInterface $user)
{
    $class = get_class($user);
    if (!$this->supportsClass($class)) {
        throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class));
    }

    return $this->loadUserByUsername($user->getUsername());
}

public function supportsClass($class)
{
    return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
}
}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用:

"SELECT p FROM InzRegisterBundle:Group p WHERE p.role='ROLE_USER'"

使用参数更新:

->createQuery(
   "SELECT p FROM InzRegisterBundle:Group p WHERE p.role=:role"
)
->setParameter('role', 'ROLE_USER')