2012-03-05 56 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