Zend framework -> database table field prefix like users.us_name

你说的曾经没有我的故事 提交于 2019-12-25 14:06:43

问题



I'm dealing with database containing of many tables, with many field prefixes (two first letters of every table), so when I have users table I cannot use "name" property ($user->name) but I can use: $user->us_name.


I's there a way to simplify things and set automagic prefix for every field of a table ?


回答1:


You'd have to extend Zend_Db_Table_Row to accomplish this. Fortunately, ZF includes a _transformColumn() method expressly for this purpose. But I'm getting ahead of myself. First, set up your table class. This assumes your database has a table called "foo_mytable":

class MyTable extends Zend_Db_Table_Abstract {
    protected $_name = 'foo_mytable';
    protected $_rowClass = 'My_Db_Table_Row';
}

Next, create your custom Row class:

class My_Db_Table_Row extends Zend_Db_Table_Row {
    protected function _transformColumn($columnName) {
        $columnName = parent::_transformColumn($columnName);
        $prefix = 'us_';
        return $prefix . $columnName;
    }
}

Now, you can do something like this (for simplicity, this example ignores MVC design ideals):

$table = new MyTable();
$records = $table->fetchAll();
foreach ($records as $record) {
    echo $record->name;
}

Assuming your table has a column named "us_name", this should work. I tested it myself. Note that in your custom table row, you might want to grab the table prefix from a config file. If you've got it stored in your registry, you could replace $prefix = 'us_'; with $prefix = Zend_Registry::get('tablePrefix');.




回答2:


I didn't know about _transformColumn(). I'm gonna hop on top of @curtisdf 's example.
I think you should override with this (not tested):

protected function _transformColumn($columnName)
{
    $tblName = $this->_table->info(Zend_Db_Table::NAME);
    $prefix  = substr($tblName, 0, 2);

    return $prefix . '_' . parent::_transformColumn($columnName);
}

Using this, you won't need to store prefixes/table-names, as they are retrieved dinamically.



来源:https://stackoverflow.com/questions/4437782/zend-framework-database-table-field-prefix-like-users-us-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!