zoukankan      html  css  js  c++  java
  • Yii2返回以主键id为键名的数组

    branch.php

    <?php
    
    namespace appmodels;
    
    use Yii;
    
    /**
     * This is the model class for table "branch".
     *
     * @property integer $id
     * @property string $name
     *
     */
    class Branch extends yiidbActiveRecord
    {
        /**
         * @inheritdoc
         */
        public static function tableName()
        {
            return 'branch';
        }
    
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [['name'], 'string', 'max' => 45],
            ];
        }
    
        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'id' => 'ID',
                'name' => 'Name',
            ];
        }
      public static function getKeyValuePairs()
        {
            $sql = 'SELECT id, name FROM ' . self::tableName() . ' ORDER BY name ASC';
        
            return Yii::$app->db->createCommand($sql)->queryAll(PDO::FETCH_KEY_PAIR);
        }
    }

    调用

    $model->getKeyValuePairs()得到如下:

    显示在前端:

    <?php
    
    use yiihelpersHtml;
    use yiiwidgetsActiveForm;
    use appmodelsBranch;
    /* @var $this yiiwebView */
    /* @var $model appmodelsPos */
    /* @var $form yiiwidgetsActiveForm */
    ?>
    
    <div class="pos-form">
    
        <?php $form = ActiveForm::begin(); ?>
    
        <?= $form->field($model, 'serial')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'branch_id')->dropDownList(Branch::getKeyValuePairs())  ?>
        
        <?= $form->field($model, 'is_enable')->checkBox() ?>
    
        <div class="form-group">
            <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        </div>
    
        <?php ActiveForm::end(); ?>
    
    </div>
  • 相关阅读:
    [YTU]_2637(编程题:类---矩形类)
    [YTU]_2625( 构造函数和析构函数)
    [YTU]_2498 (C++类实现最大数的输出)
    [YTU]_2433( C++习题 对象数组求最大值)
    [YTU]_2432( C++习题 对象数组输入与输出)
    AC自动机模板1
    trie字典树
    KMP模板
    Count(广工14届竞赛)
    zyb的面试(广工14届比赛)
  • 原文地址:https://www.cnblogs.com/xiong63/p/7857985.html
Copyright © 2011-2022 走看看