Zend Framework: How to concatenate two columns and still use fetchPairs()?

心不动则不痛 提交于 2019-12-02 00:02:41

问题


I have a form with a select element that I need to populate with values from a database. Specifically, the name and id of the current users. The fetchPairs() function works great for this! However, I need to concatenate the value from the first_name column and the last_name column and display this as the option label. Is there a way to do it and still use fetchPairs()? If not, how can I achieve the same result? Here's an excerpt of the code that is currently working:

<?php // excerpt

class Default_Form_AddUser extends Zend_Form
{
    public function init()
    {
        $this->addElement('select', 'user', array(
            'label'      => 'Select user:',
            'required'   => true,
            'multiOptions' => $this->_getSelectOptions()
        ));
    }

    protected function _getSelectOptions()
    {
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = $db->select()->from('users', array('id', 'first_name'));
        $roleOptions = $db->fetchPairs($select);
        return $roleOptions;
    }
}

回答1:


protected function _getSelectOptions()
{
    $db     = Zend_Db_Table::getDefaultAdapter();
    $select = $db->select()->from('users', array(
        'id',
        'name' => new Zend_Db_Expr("CONCAT(first_name, ' ', lastname)"),
    ));

    return $db->fetchPairs($select);
}



回答2:


This is only an idea, and fully untested, but you could try to use a Zend_Db_Expr:

$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()->from(
   'users', 
    array('id', "CONCAT_WS(' ', first_name, last_name")
);
$roleOptions = $db->fetchPairs($select);
return $roleOptions;

From the Zend_Db documentation:

Example 15.55. Examples of specifying columns containing expressions

An expression with parentheses implicitly becomes a Zend_Db_Expr.



来源:https://stackoverflow.com/questions/1799577/zend-framework-how-to-concatenate-two-columns-and-still-use-fetchpairs

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