Yii2返回以主键id为键名的数组

Posted 岁月如歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2返回以主键id为键名的数组相关的知识,希望对你有一定的参考价值。

branch.php

<?php

namespace app\\models;

use Yii;

/**
 * This is the model class for table "branch".
 *
 * @property integer $id
 * @property string $name
 *
 */
class Branch extends \\yii\\db\\ActiveRecord
{
    /**
     * @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 yii\\helpers\\html;
use yii\\widgets\\ActiveForm;
use app\\models\\Branch;
/* @var $this yii\\web\\View */
/* @var $model app\\models\\Pos */
/* @var $form yii\\widgets\\ActiveForm */
?>

<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>

 

以上是关于Yii2返回以主键id为键名的数组的主要内容,如果未能解决你的问题,请参考以下文章

thinkphp5.0 column多字段问题

PHP常用函数

从带有键名的 JSON 中提取值在 bigquery 中包含 #

array_merge

如何使用 Angular 在 HTML 中访问没有键名的数组对象

PHP树-不需要递归