C4PO
C4PO

Reputation: 199

Using Doctrine2/Zend Framework 1.11 with column containing underscore

I am in the process of refactoring a website to Zend Framework 1.11/Doctrine 2 and have a number of legacy tables containing column names with underscores (e.g. plant_id). (Was initially quite intimated, but am steadily being quite impressed with Doctrine!)

I have successfully set up a doctrine entity (following WJ Gilmores' excellent book Easy PHP with the Zend Framework) but are having issues when we use Doctrine's findOne magic finder with the legacy column names that include underscore

The code

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

returns an error

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

(Incidentally, Doctrine otherwise seems fine - we have created an Entity with this as our column name, and can retrieve this column.)

We have solved this in the interim by building a query with query builder.

Is there any other simpler solution that does not require quite so much code other than changing the whole whole table to remove the underscore (not easy, as there is lots of legacy code we would have to rework)?

Upvotes: 2

Views: 477

Answers (2)

Phil
Phil

Reputation: 164909

You don't use the column name in the magic finders but the entity property. The property names don't need to match the actual column names at all.

Try something like the following...

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

Then, you can simply use

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

Were you to use a non-primary key column, you simply use the property name, eg

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

and via the repository

$repo->findOneBySomeProperty($val)

You can also use the array method

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

Upvotes: 3

Kees Schepers
Kees Schepers

Reputation: 2248

There is one thing you could do, but it might not be the best approach. Since Doctrine proberly guesses that a underscore is for camelcasing.

You can create your own repository class. When you create this class you implement a method called findyByPlant_Id($id) and you create a qb in your method:

<?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();
  }
}
?>

I have to say I didn't check syntax, but it at least pushes you in the right direction if you like this solution. There might be better solutions...

Upvotes: 2

Related Questions