为什么连接表在symfony2中不起作用?

时间:2014-11-06 18:08:03

标签: php symfony doctrine-orm

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;



}

我的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();

    }


}

我希望按列&#39; user_id&#39;制作联接表用户和帖子在表&#39;帖子&#39;。接下来我使用queryBuilder进行查询:

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


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

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

我得到了:

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)

为什么user-&gt;路径为空?如何在表格中进行此连接

1 个答案:

答案 0 :(得分:1)

Doctrine在使用帮助函数(例如find()findAll()时使用延迟加载方法时会根据需要获取相关实体,但是当您使用查询生成器时,您正在创建显式查询/结果不要被Doctrine的lazy-loader处理。

使用查询构建器时,必须显式加入其他相关实体:

$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();

请注意,您可以轻松使用innerJoin代替leftJoin,但如果您有任何潜在的Post项与空关联,则可以使用/** * @ORM\ManyToOne(targetEntity="Acme\PostBundle\Entity\User", inversedBy="posts") * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ protected $user;

您还必须确保您的实体映射是正确的:

id

否则,Doctrine会尝试将帖子的id与用户的LEFT JOIN Post ON Post.id = User.id进行匹配。 (当它到达原始查询时类似{{1}})