简体   繁体   中英

Zend Framework 1.12: _setupPrimaryKey method of Zend Table

I'm working on fixing bug related to Zend_Db_Table models. The problem that I faced with is that $_primary property of the Zend_Db_Table ancestor mysteriously being changed after you call insert, update etc.

Let's say I have the following value in this field:

Class Model_Book extends App_Base_FileForAcs implements App_Interface_OnixDataSource, App_Interface_ApiDataSource, App_Interface_DbGateway
{
protected $_name = 'book';
protected $_primary = 'book_id';
...
}

If I check $_primary after insert operation it will contain:

array(1) {
[1]=>
string(7) "book_id"
}

This transformation happens in _setupPrimaryKey method of Zend_Db_Table_Abstract class. Could you explain why this field should be transformed to array and why array starts with not 0 index?

ZF internally uses an array to define the primary key in order to manage compound keys. It's described here:

http://framework.zend.com/manual/1.12/en/zend.db.table.html#zend.db.table.defining.primary-key

The code in _setupPrimaryKey either casts your string to an array with index 1, or if it's already an array, does an array_unshift($this->_primary, null) followed by unsetting the _primary[0] to make it 1-based.

To get the primary key (as an array at all times), you'll find more information here: Get Primary Key out of Zend_Db_Table_Rowset Object - that includes how to get it from the table object too.

So, in short - the primary key is always an array, but ZF allows you to define it as a string, for convenience. You never described your bug, but if you rely on the primary key being a string, reading the $_primary directly, you should probably refactor to get the key using $objZenDbTable->info('primary') instead, fully expecting an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM