Setting a required value in Doctrine model
Is it p开发者_如何转开发ossible to set a constraint in a Doctrine model, so that all queries using that model include this requirement? For example, if I have a Car model and I want to ensure that all results retrieved using the model have active = 1
set in the database. I could define this in each individual query, but it seems like there's probably a better way.
Cheers!
I would take advantage of their amazing pre and post hooks inside the model.
Example:
class Model_Car extends Model_Base_Car
{
public function preDqlSelect(Doctrine_Event $event)
{
$event->getQuery()->addWhere("active = ?", 1);
}
}
Although I did not test this, it should work. I have used the pre and post hooks a lot to make my life easier in the past. For instance, I had a model that wanted to save the REMOTE_ADDR on each insert and update, so I did the following to make my life easier:
class Model_Example extends Model_Base_Example
{
public function preInsert(Doctrine_Event $event)
{
$this->created_ip = $this->_getRemoteIp();
}
public function preUpdate(Doctrine_Event $event)
{
$this->updated_ip = $this->_getRemoteIp();
}
protected function _getRemoteIp()
{
return ip2long($_SERVER['REMOTE_ADDR']);
}
}
hope this helps!
I would do this in query ->andWhere('active = ?', 1), but if you are tring to do this "tricky way", you can always build your own hydrator.
here is an answer to your question: subclassing the doctrine query object.
http://brentertainment.com/2010/03/03/doctrine_query_extra-extending-the-doctrine-query-object/
精彩评论