0

I'm doing a query and I get a strange error that I don't understand how it works or why it happens.

I'm new to symfony so bare with me.

My Goal is: To Select for a table but I want to exclude the current users data.

    /**
 * @param int $getIndex
 * @param User $user
 * @return int|mixed|string
 */
public function findByIndex(int $getIndex, User $user)
{
    $queryBuilder = $this->createQueryBuilder('a');

    $query = $queryBuilder->where(
        $queryBuilder->expr()->eq('a.index', $getIndex),
        $queryBuilder->expr()->neq('a.user', $user->getId())
    )
    ->getQuery();

    return $query->getResult();
}

I want to return the results but I don't want the current user answer.

And the error is thrown from the neq.

"[Syntax Error] line 0, col 72: Error: Expected end of string, got 'b6f037' File:/home/wwwroot/htdocs/vendor/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php Line: 52"

This is what i pass in

public function __construct(
    UserRepository $userRepository,
    AnswerRepository $answerRepository,
    TokenStorageInterface $tokenStorage
) {
    $this->userRepository = $userRepository;
    $this->answerRepository = $answerRepository;
    $this->user = $tokenStorage->getToken()->getUser();
}

$results = $this->answerRepository->findByIndex($dto->getIndex(), $this->user);
 

How can i fix this issue ?

1 Answers1

2

I think the root of the problem is that you are passing the user id instead of the user entity (DQL uses objects). Doctrine will handle the index in the resulting query. Also always set your variables as parameters (Doctrine will properly escape values).

Try something like the following:

  public function findByIndex(int $getIndex, User $user)
  {
    $queryBuilder = $this->createQueryBuilder('a');

    $query = $queryBuilder
      ->where($queryBuilder->expr()->eq('a.index', ':index'))
      ->andWhere($queryBuilder->expr()->neq('a.user', ':user'))
      ->setParameter('index', $getIndex)
      ->setParameter('user', $user)
      ->getQuery();

    return $query->getResult();
  }
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31
  • Hey. This kinda of works. I'm not sure why i still get the actually logged in users answers. Is the `->neq` wrong here ? The idea is; 1. Users Logs-in in. 2. User gives an answer 3. This user can upvote other peoples answers but SHOUL NOT (neq) see his own answers. When i try it wit this query I still get his inputed values. – ichbinbobderbaumeister Apr 30 '21 at 20:19
  • Do you maybe know the reason ? – ichbinbobderbaumeister May 01 '21 at 18:06
  • I'm not sure about that part without knowing the entity relationships. Try flipping the expressions `->where(...->neq(...))->andWhere(...->eq(...))`. This is technically a different question that has answers already. Did my solution resolve the error you asked about? – Arleigh Hix May 01 '21 at 18:28