engilexial
engilexial

Reputation: 153

Why join table is not working in symfony2?

My Post.php

<?php
// src/Acme/UserBundle/Entity/User.php

namespace Acme\PostBundle\Entity;


use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="posts")
 */
class Post
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     *
     * @ORM\Column(type="integer")
     */
    public $user_id;
    /**
     * @ORM\ManyToOne(targetEntity="Acme\PostBundle\Entity\User", inversedBy="posts")
     * @ORM\JoinColumn(name="id", referencedColumnName="id")
     */
    protected $user;
    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank(message="Введите текст")
     * )
     */
    protected $text;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $address;
    /**
     *
     * @ORM\Column(type="datetime")
     */
    protected $date;



}

And my User.php:

<?php
// src/Acme/UserBundle/Entity/User.php

namespace Acme\PostBundle\Entity;


use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;
    /**
     *
     * @ORM\Column(type="string")
     */
    protected $path;

    /**
    * @ORM\OneToMany(targetEntity="Acme\PostBundle\Entity\Post", mappedBy="users")
    */
    protected $posts;

    public function __construct() {

        $this->posts = new ArrayCollection();

    }


}

I want make join table users and posts by column 'user_id' in table 'posts'. Next i make query using queryBuilder:

    $repository = $this->getDoctrine()->getManager()->getRepository('AcmePostBundle:Post');


    $queryPosts = $repository->createQueryBuilder('p')
                   ->orderBy('p.id', 'DESC')
                   ->getQuery();

    return new Response(var_dump($queryPosts->getResult()));

And i'm get:

object(Acme\PostBundle\Entity\Post)[476]
      protected 'id' => int 1
      public 'user_id' => int 1
      protected 'user' => 
        object(Proxies\__CG__\Acme\PostBundle\Entity\User)[475]
          public '__initializer__' => 
            object(Closure)[469]
              ...
          public '__cloner__' => 
            object(Closure)[470]
              ...
          public '__isInitialized__' => boolean false
          protected 'id' => int 1
          protected 'path' => null
          protected 'posts' => null
      protected 'text' => string 'Test' (length=4)
      protected 'address' => string 'Test' (length=4)
      protected 'date' => 
        object(DateTime)[477]
          public 'date' => string '2014-11-06 14:39:13' (length=19)
          public 'timezone_type' => int 3
          public 'timezone' => string 'Europe/Kiev' (length=11)

Why user->path is null? How make to make this joins in table

Upvotes: 0

Views: 464

Answers (1)

sjagr
sjagr

Reputation: 16502

Doctrine utilizes lazy-loading methodologies when using the helper functions such as find() or findAll() which fetch related entities on demand, but when you use the Query Builder, you are creating explicit queries/results that do not get handled by Doctrine's lazy-loader.

When using the Query Builder, you must explicitly join the other related entities:

$queryPosts = $this->getDoctrine()->getManager()->createQueryBuilder()
               ->select('p, u')
               ->from('AcmePostBundle:Post', 'p')
               ->leftJoin('p.user','u') // handles the ManyToOne association automatically
               ->orderBy('p.id', 'DESC')
               ->getQuery();

Note that you could easily use innerJoin instead of leftJoin but settled for that in case you had any potential Post items with a null association.

You also must make sure your Entity Mapping is correct:

/**
 * @ORM\ManyToOne(targetEntity="Acme\PostBundle\Entity\User", inversedBy="posts")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

Or else Doctrine will attempt to match the id of the Post against the id of the User. (something like LEFT JOIN Post ON Post.id = User.id by the time it reaches a raw query)

Upvotes: 1

Related Questions