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()得到如下:

Yii2返回以主键id为键名的数组_第1张图片

 

显示在前端:

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 */
?>

class="pos-form"> field($model, 'serial')->textInput(['maxlength' => true]) ?> field($model, 'branch_id')->dropDownList(Branch::getKeyValuePairs()) ?> field($model, 'is_enable')->checkBox() ?>
class="form-group"> isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

 

转载于:https://www.cnblogs.com/xiong63/p/7857985.html

你可能感兴趣的:(数据库,php,前端)