2014-01-06 56 views
1

我在我的數據庫中有兩個表,我想加入這兩個表來顯示我的視圖中的數據,但我沒有找到解決方案。如何加入表原則symfony2

這是我的第一個實體下方

/** 
* @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"; 

給出的第二個實體:

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; 
} 

在我的控制器我想加入該表來獲取信息。

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

任何解決方案,請?

+0

您的模式不正確。你永遠不應該在實體中寫somethig_id。您通過引用綁定對象,而不是數據庫ID。請仔細閱讀文檔。 – 1ed

回答

6

寫出漂亮&乾淨的代碼,

回答之前,我建議你修復代碼中的下列問題,

  • 類的名稱應該是駝峯&奇異(Classified而不是classifiedRegion而不是regions
  • 試圖找到一個更清潔的方式來設置country_id(因爲protected $country_id=107;不做敏感。同爲user_id

所以,爲了與它相關的區域,讓您的分類的實體,您對,

首先,改變(在你Classified類)

/** 
* @ORM\Column(type="integer") 
*/ 
protected $region_id="null"; 

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

,並添加到您的Region實體,

/** 
* @ORM\OneToMany(targetEntity="Classified", mappedBy="region") 
*/ 
protected $classifieds; 

採取在文檔的Databases and DoctrineEntity Relationships/Associations部分從深層次看,以瞭解如何使用Doctrine定義實體的關聯。

+0

你可能是指'OneToMany(targetEntity =「Classified」,mappedBy =「region」)' – Touki

+0

是的。固定:)謝謝。 –

+0

對不起,我沒有解釋我的問題,我有表區域充滿了信息,所以我必須提取這些信息,當我結合兩個表(例如,我想獲取變量$ regionname時classified.region_id = region.region_id ) – hamza437