我有一个Listener,我可以在数据库中插入数据,但我无法在我的User存储库中访问我的自定义方法(countByUsername)。但是,如果我取消注释,则注释的UserTransfer部分(与存储库方法相同)确实有效。
UserTransfer.php
<?php
namespace PortalBundle\EventListener;
use PortalBundle\PortalBundle;
use Doctrine\ORM\OptimisticLockException;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use PortalBundle\Entity\User;
class UserTranfer
{
protected $em;
public function __construct(\Doctrine\ORM\EntityManager $em)
{
$this->em=$em;
}
public function transfer(AuthenticationEvent $event){
$token = $event->getAuthenticationToken();
$user = $token->getUser();
$repository = $this->em->getRepository('PortalBundle:User');
$count = $repository->countByUsername($user->getUsername());
/*$qb = $repository->createQueryBuilder('u');
$qb->select('count(u._id)');
$qb->where('u._username = :username');
$qb->setParameter('username', $user->getUsername());
$count=$qb->getQuery()->getSingleScalarResult();*/
if($count !== "0") {
return;
}
$newUser = new User();
$newUser->setUsername($user->getUsername())->setFullname($user->getFullname());
$this->em->persist($newUser);
try {
$this->em->flush();
} catch (OptimisticLockException $e) {
}
}
}
UserRepository.php
<?php
namespace PortalBundle\Repository;
class UserRepository extends \Doctrine\ORM\EntityRepository
{
public function countByUsername($username)
{
$qb = $this->createQueryBuilder('u');
$qb->select('count(u._id)');
$qb->where('u._username = :username');
$qb->setParameter('username', $username);
return $qb->getQuery()->getSingleScalarResult();
}
}
User.php的最开始
<?php
namespace PortalBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User entity
* @ORM\Entity(repositoryClass="PortalBundle\Repository\UserRepository")
* @ORM\Table(name="user")
* @ORM\Entity
*/
class User
{
返回的错误标识为Undefined method 'countByUsername'. The method name must start with either findBy or findOneBy!
答案 0 :(得分:1)
在User
课程中,您定义了ORM\Entity
注释两次。
最后一个是由Doctrine解析的,它缺少了存储库。
这将有效:
/**
* User entity
* @ORM\Entity(repositoryClass="PortalBundle\Repository\UserRepository")
* @ORM\Table(name="user")
*/
class User
{