2012-03-05 50 views
2

我正在將網站重構爲Zend Framework 1.11/Doctrine 2,並且有許多包含具有下劃線的列名的遺留表(例如plant_id)。 (最初是相當透徹的,但是我對教義印象深刻!)使用含有下劃線的列的Doctrine2/Zend Framework 1.11

我已經成功地建立了一個學說實體(遵循WJ Gilmores的優秀着作Easy PHP和Zend Framework),但在使用Doctrine's findOne神奇取景器與包括傳統的列名強調

代碼

$plant = $this->em->getRepository('Entities\Plant') 
->findOneByPlant_id('3571'); 

返回一個錯誤

Message: Entity 'Entities\Plant' has no field 'plantId'. You can therefore not call 'findOneByPlant_id' on the entities' repository 

(順便說一句,Doctrine否則看起來很好 - 我們創建了一個實體,並將其作爲我們的列名稱,並且可以檢索此列。)

我們通過使用查詢構建器構建查詢來解決此問題。

是否還有其他更簡單的解決方案,除了更改整個整個表格以刪除下劃線(不容易,因爲有大量遺留代碼,我們將不得不返回),不需要太多的代碼?

回答

3

你不使用神奇的發現者列名稱,但實體屬性。屬性名稱根本不需要匹配實際的列名稱。

嘗試類似如下的...

/** 
* @Entity 
*/ 
class Plant 
{ 
    /** 
    * @Id 
    * @Column(name="plant_id", type="integer") 
    */ 
    private $id; 

然後,您可以簡單地使用

$plant = $plantRepository->find(3571); 

是你使用非主鍵列,只需使用屬性名,例如

/** 
* @Column(name="some_col_with_underscores") 
*/ 
private $someProperty; 

,並通過庫

$repo->findOneBySomeProperty($val) 

您也可以使用數組方法

$repo->findOneBy(array('someProperty' => $val)); 
+0

Brill。很有幫助。 – C4PO 2012-03-06 11:44:09

2

有一件事你可以做,但它可能不是最好的方法。由於學說精確地猜測一個下劃線是用於駝峯式的。

您可以創建您的own repository class。當你創建這個類,你實現了一個名爲findyByPlant_Id($ id)的方法,並創建你的方法QB:

<?php 
class PlantRepository extends Doctrine\ORM\Repository { 
    function findByPlant_Id($id) { 
    $qb = $this->createQueryBuilder('p')->where('p.id = :id')->setParameter('id' ,$id); 

    return $qb->getQuery()->getOneOrNullResult(); 
    } 
} 
?> 

我不得不說我沒有檢查語法,但它至少推您在正確的方向,如果你喜歡這個解決方案有可能有更好的解決方案...

+0

第一個答案我想是在設置東西更好,但你的微調將是有益的其它地方。謝謝! – C4PO 2012-03-06 11:44:50