Updating a Magento Collection with Zend_db objects.

So, I needed to update a magento adminhtml grid.  I took a look at the database and it seemed pretty simple.  There is a table with all of the main information, and a history table that is referenced when an addHistory function is called on the collection.

The old add history function looked like this.

[sourcecode language=”php”]
public function addHistory()
{
if ($this->_hasHistory) {
return $this;
}
$this->_hasHistory = true;
$this->getSelect()->join(array(‘h’=>$this->getTable(‘ugiftcert/history’)), ‘h.cert_id=main_table.cert_id’, array(‘ts’, ‘amount’, ‘customer_id’, ‘customer_email’, ‘order_id’, ‘order_increment_id’, ‘order_item_id’, ‘user_id’, ‘username’))
->where("h.action_code=’create’");
return $this;
}
[/sourcecode]

The history table had action_code of create and update, and I needed to bring in the date for the update actions where they existed. Since updates always happen after create, I figured I could take the max of the ts column, which is the date column, where action code is create or update.

I did some documentation searching and found several magento collection functions that kept throwing “method not found” errors including groupByAttribute to name one. I was close, but it wasn’t quite working right. Then after consulting a colleague, Joseph Piche, he noticed that it was not a magento collection object I was trying to change, but a Zend_Db object. I had the function mostly working, but couldn’t get the group by in my sql to work correctly. Turns out, the method I wanted was named simply “group.” With this information, the update became quite trivial and my final function looks like this:

[sourcecode language=”php”]
public function addHistory()
{
if ($this->_hasHistory) {
return $this;
}
$this->_hasHistory = true;
$this->getSelect()->join(array(‘h’=>$this->getTable(‘ugiftcert/history’)), ‘h.cert_id=main_table.cert_id’, array(‘amount’, ‘customer_id’, ‘customer_email’, ‘order_id’, ‘order_increment_id’, ‘order_item_id’, ‘user_id’, ‘username’))
->from(null, array(‘ts’ => ‘MAX(ts)’))
->group(array(‘main_table.cert_id’))
->where("h.action_code=’create’ or h.action_code=’update’");
return $this;
}
[/sourcecode]

Lesson learned: Know the object you’re trying to modify before using methods on it. A simple look at the class inheritance which shows:

[sourcecode language=”php”]
class Unirgy_GiftCert_Model_Mysql4_Cert_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
[/sourcecode]

and I would have known where to search for methods to make my life a lot easier while searching for the group by method.

Leave a Reply

Your email address will not be published. Required fields are marked *