Symfony3按关系搜索

时间:2016-10-25 15:47:16

标签: symfony orm doctrine-orm

我希望通过令牌找到用户。我有一对多的关系。我的学说配置文件:

AppBundle\UserEntity:
    type: entity
    table: null
    repositoryClass: AppBundle\Repository\UserEntityRepository
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        username:
            type: string
            length: 255
            unique: true
        password:
            type: string
            length: 255
            nullable: true
        salt:
            type: string
            length: 255
            unique: true
        email:
            type: string
            length: '100'
    lifecycleCallbacks: {  }
    oneToMany:
      token:
        targetEntity: TokenEntity
        mappedBy: user
        fetch:  EAGER



AppBundle\TokenEntity:
    type: entity
    table: null
    repositoryClass: AppBundle\Repository\TokenEntityRepository
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        value:
            type: string
            length: 255
            unique: true
    lifecycleCallbacks: {  }
    manyToOne:
      user:
        targetEntity: UserEntity
        inversedBy: token
        joinColumns:
          user_id:
            referencedColumnName: id

我尝试按标记搜索用户:

UserEntityRepository.php

 <?php 

class UserEntityRepository extends EntityRepository 
{
  public function loadUserByToken(string $token)
 {
   $repository = $this->_em->getRepository('AppBundle:UserEntity');
   $user = $repository->findOneBy(['token'=>1]);

   return $user;
 }
}

Symfony抛出异常:

  

您无法搜索关联字段   &#39; AppBundle \ Entity \ UserEntity#token&#39;,因为它是反面的   一个协会。查找方法仅适用于拥有副关联。

有什么问题?如何修复这种关系?用户应该只有很少的令牌。

你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

要解决此问题,您应该创建一个关系查询:

$user = $repository->createQueryBuilder('u')
    ->innerJoin('AppBundle:TokenEntity', 't')
    ->where('t.value = :token')
    ->setParameter('token', $token)
    ->getQuery()
    ->getOneOrNullResult();