views:

355

answers:

1

Is there a way to add a default scope to a Zend_Db_Table_Abstract based model.

I want to be able to query a model with some conditions taken as default.

e.g.

  • deleted = false
  • order name asc
+1  A: 

You can override the Zend_Db_Table_Abstract:: _fetch() method and modify the generated Zend_Db_Table_Select in there before retrieving the rows from the database adapter. As far as I know all fetch*-methods and find() in Zend_Db_Table_Abstract boil down to this generic row-retrieval-method (besides Zend_Db_Table_Abstract::fetchNew() naturally), so your modified code will be called everytime rows are retrieved from the database.

/**
 * Support method for fetching rows.
 *
 * @param  Zend_Db_Table_Select $select  query options.
 * @return array An array containing the row results in FETCH_ASSOC mode.
 */
protected function _fetch(Zend_Db_Table_Select $select)
{
    $select->where('deleted = false')->order('name asc');
    return parent:: _fetch($select);
}
Stefan Gehrig
I read this earlier here but cant seem to get it working :Shttp://www.zendframeworkinaction.com/2008/01/30/zend_db_table_abstract-in-version-15/very odd
sfusion
What does "cant seem to get it working" mean? Are you getting error messages or wrong results or nor result at all? Have you tried to debug what's going on?
Stefan Gehrig
Try adding a var_dump($select->__toString()) in the method above - just before the call to the parent method and look what the generated SQL string looks like.
Stefan Gehrig
the var_dump reveals that it is putting the scope into the sql... but it causes calls to findDependentRowset to fail.
sfusion
Do you get any error message on calling findDependentRowset()?
Stefan Gehrig
The scope works perfectly when querying the model directly. But when I try to access the model through findDependentRowset() none of the scope I set up in the model is used. findDependentRowset() must use a different fetch action maybe?
sfusion
It's weird it does use Zend_Db_Table_Abstract::_fetch() so it shouldn't reset the query, try to add some var_dumps directly on the method in the Zend Class to see where it's losing the value.
Chris
I resolved the problem. The scope was working correctly! I am an idiot and had a column called TIMESTAMP, so instead of ordering by TIMESTAMP I had to order by TableName.TIMESTAMP.
sfusion