Reputation: 486
I want find user by token. I have one to many relations. My doctrine configuration file:
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
I trying search user by token :
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 throw exception :
You cannot search for the association field 'AppBundle\Entity\UserEntity#token', because it is the inverse side of an association. Find methods only work on owning side associations.
What is wrong ? How repair this relations ? User should have few tokens.
Can you help me ?
Upvotes: 1
Views: 73
Reputation: 9575
To fix that you should create a relational query:
$user = $repository->createQueryBuilder('u')
->innerJoin('AppBundle:TokenEntity', 't')
->where('t.value = :token')
->setParameter('token', $token)
->getQuery()
->getOneOrNullResult();
Upvotes: 2