symfony query question
In the modules actions, what is the best way to selec开发者_运维技巧t 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();
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.
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?
精彩评论