dongza1708 2015-12-07 21:08
浏览 28

Zend Framework 1.12:Zend Table的_setupPrimaryKey方法

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?

  • 写回答

1条回答 默认 最新

  • dongsuoxi1790 2015-12-09 11:26
    关注

    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.

    评论

报告相同问题?