如何连接表doctrine symfony2

ham*_*437 1 symfony doctrine-orm

我在我的数据库中有两个表,我想加入这个2表来显示我的视图中的数据,但我没有找到解决方案.

这是我下面给出的第一个实体

/**
 * @ORM\Entity
 */
class classified   
{
     /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $classified_id;

    /**
     * @ORM\Column(type="integer")
    */
    protected $user_id=0;

    /**
     * @ORM\Column(type="string")
    */
    protected $firstname="null";

    /**
     * @ORM\Column(type="integer")
     */
    protected $region_id="null";
Run Code Online (Sandbox Code Playgroud)

第二个实体:

class regions  
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
    */
    protected $region_id;

    /**
     * @ORM\Column(type="string")
    */
    protected $regionname;

    /**
     * @ORM\Column(type="integer")
    */
    protected $country_id=107;
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我想加入该表以获取信息.

$em = $this->getDoctrine()
                   ->getEntityManager();

        $classified = $em->createQueryBuilder()
                    ->select('b')
                    ->from('BlogBundle:classified',  'b')
                    ->addOrderBy('b.classifiedaddeddate', 'DESC')
                    ->getQuery()
                    ->getResult();
        return $this->render('BlogBundle:Page:index.html.twig', array(
            'classified' => $classified
        ));
Run Code Online (Sandbox Code Playgroud)

有解决方案吗?

Ahm*_*ani 6

写出漂亮干净的代码,

在回答之前,我建议您在代码中修复以下问题,

  • 类的名称应与驼峰奇异(Classified而不是classifiedRegion代替regions)
  • 尝试找到一种更清晰的方式来设置country_id(因为protected $country_id=107;不会产生感觉.相同user_id)

所以,为了让你的分类实体与其相关的区域,你必须,

一,改变(在你Classified班上)

/**
 * @ORM\Column(type="integer")
 */
protected $region_id="null";
Run Code Online (Sandbox Code Playgroud)

/**
 * @ORM\ManyToOne(targetEntity="Region", inversedBy="classifieds")
 * @ORM\JoinColumn(name="region_id", referencedColumnName="region_id")
 */
protected $region;
Run Code Online (Sandbox Code Playgroud)

并添加到您的Region实体,

/**
 * @ORM\OneToMany(targetEntity="Classified", mappedBy="region")
 */
protected $classifieds;
Run Code Online (Sandbox Code Playgroud)

深入了解文档的数据库和学说章节中的实体关系/关联部分,以了解如何使用Doctrine定义实体关联.