我想做一个下拉列表,可以显示两个颜色的浓度
这是我的代码:

  $list = CHtml::listData(Coa::model()->findAllBySql("SELECT id, concat(name,' - ',saldo) as info FROM coa where id_type = 1"),'id','info');
  echo CHtml::dropDownList('id_coa','id', $list, array('prompt'=>'choose account','class'=>'form-control'));

表由id、id_type、name和saldo组成。
我想知道名字和萨尔多,
然后把它放到下拉选项中
我尝试了findAllBySql中的代码,它工作得很好
当我把它放在yii身上时,它不起作用。

最佳答案

在model类中创建getter函数,该函数将在单个字符串中返回两个字段的值,如下所示:

class Coa extends CActiveRecord {
    // ...
    public function getNamesaldo() {
        return sprintf('%s %s', $this->name, $this->saldo);
    }
    // ...
}

然后在不使用任何concat函数的情况下正常获取记录,但这两个字段都应该在select查询中。因此,模型函数可以在一个字符串中返回两个值:
$model_data = Coa::model()->findAllBySql(
    "SELECT id, name, saldo FROM coa where id_type = 1");

现在,这里调用listData并将model属性idgetter名称指定为:
$list = CHtml::listData($model_data, 'id', 'namesaldo');
echo CHtml::dropDownList('id_coa', 'id', $list, array(
    'prompt' => 'choose account', 'class' => 'form-control'));

仅此而已:)

关于php - 在yii中使用listdata的Concat 2列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31341997/

10-12 12:40
查看更多