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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.