【问题标题】:Symfony3 search by relationsSymfony3 按关系搜索
【发布时间】:2017-03-07 18:14:41
【问题描述】:

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

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 抛出异常:

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

怎么了?如何修复这种关系?用户应该有很少的令牌。

你能帮帮我吗?

【问题讨论】:

    标签: symfony orm doctrine-orm


    【解决方案1】:

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

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

    【讨论】:

    • 这行得通!我想,通过 ->findOneBy 应该可以工作,但是这个解决方案很好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2015-10-30
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多