views:

46

answers:

2

In the modules actions, what is the best way to select records based on an index other than the primary key id?

$this->city = Doctrine::getTable('City')->find(array($request->getParameter('city')));

This always returns a query with WHERE City.id= instead of WHERE City.city=

Do I have to do something like

$q = Doctrine_Query::create()
    ->from('City j')
    ->where('j.city = ?', $request->getParameter('city'));
    $this->city=$q->execute();
+3  A: 

Why not just use the magic methods?

<?php
$city = Doctrine::getTable('City')->findOneByCity($request->getParameter('city');

A good practise is to wrap it in a check like this:

<?php
$this->forward404Unless($city = Doctrine::getTable('City')->findOneByCity($request->getParameter('city'));

This should be done in your action.

Was that what you meant?

phidah
thanks that worked
Ite Code
please accept the answer and give an upvote if you could use it :-)
phidah
+1  A: 

find() method only finds a record by a primary key.

You are able to find records by other fields with findBy*/findOneBy* methods just like @phidah mentioned (so it's findOneByCity in your case).

However, you shouldn't use finder methods in your final code. From doctrine's documenation:

These are very limited magic finders and it is always recommended to expand your queries to be manually written DQL queries. These methods are meant for only quickly accessing single records, no relationships, and are good for prototyping code quickly.

Read more about magic finders here: http://www.doctrine-project.org/documentation/manual/1_2/nl/dql-doctrine-query-language:magic-finders

I'd rather put a short call to a model method in your action.

Action:

$this->city = CityTable::getByName($request->getParameter('city'));

Model:

public static function getByName($cityName)
{
    return Doctrine_Core::getTable('City')
      ->createQuery('c')
      ->where('c.city = ?', $cityName)
      ->fetchOne();
}

As long as you give appropriate name to your method, which shows its intent, your code is far more readable.

kuba
it is more readable. thank you very much for the direction
Ite Code