Lukaszy
Lukaszy

Reputation: 331

How to change Query to contain data from joined table?

I have simple Entity:

id
username
guard

"guard" is id of another user from the same Entity. I have to render view with simple table:

username | name of guard
-------------------------
John     | Bob

I tried to do that by query:

$ur = $this->getDoctrine()->getRepository(User::class)->createQueryBuilder('u')
            ->leftJoin(User::class, 'u2', \Doctrine\ORM\Query\Expr\Join::WITH, 'u.guard = u2.id')
            ->getQuery()
            ->getResult();

but it gives me just id and username, no joined data. I know that entire query should be like:

SELECT 
  * 
FROM 
  user u0_ 
  LEFT JOIN user u1_ ON (u0_.guard = u1_.id)

but I can't find the way to implement that by QueryBuilder and then to access that in twig template.

Regards

Upvotes: 0

Views: 317

Answers (1)

Lukaszy
Lukaszy

Reputation: 331

OK, I found out the mistakes in my code:

  1. I tried to set that OneToOne realtion and that was small mistake, but I needed here ManyToOne.

    /**
     * Many Users have One Guard (User)
     * @ORM\ManyToOne(targetEntity="User")
     */
    private $guard = 0;

  1. When I did that Symfony automatically force me to change my code and in column "guard" I have to insert User object.

  2. After that I don't need join anymore - just select data from table and guard column includes User object which I can use in Twig, etc.


    namespace AppBundle\Entity;
    use Doctrine\ORM\EntityRepository;

    class UserRepository extends EntityRepository
    {
        public function findAllDB()
        {
            $qb = $this->createQueryBuilder('u');
            $query = $qb->getQuery();
            return $query->execute();
        }
    }

Upvotes: 0

Related Questions