Yii2 ArrayHelper :: map左连接选择

时间:2018-07-20 07:41:17

标签: php jquery yii2

我有用户,订单和计划。客户购买计划时,数据保存在orders中,计划保存在account_plan中,用户信息位于表users中。表orders中的计划是何时开始和何时过期。我用于Select2 ArrayHelper,但不显示该列 这是一个查询

 $masAcc[0] = Yii::t('app', 'Choose plan');
 $masAcc['----------------'] = 
ArrayHelper::map(
\backend\models\Orders::find()
->select('orders.*,account_planLang.name as name')
->leftJoin('orders_props','`orders_props`.`order_id`= `orders`.`id`')
->leftJoin('account_plan','`orders_props`.`product_id`=`account_plan`.`id`')
->leftJoin('account_planLang','account_plan.id=account_planLang.plan_id')
->where('`orders`.`dt_end`<CURDATE() + INTERVAL 5 DAY AND `orders`.`dt_end`<CURDATE()')
->all(), 'id', 'name');

,但错误是: Getting unknown property: backend\models\Orders::name 这是Select2:

 $form->field($model, 'account')->widget(Select2::classname(), [
                        'model' => $model,
                        'theme' => 'bootstrap',
                        'options' => [
                            'placeholder' => Yii::t('app', 'app.choose'),
                            'class' => 'form-control select2'
                        ],
                        'data' => $masAcc,
                        'pluginOptions' => [
                            'allowClear' => true,
                        ],
                    ]);
                    }

2 个答案:

答案 0 :(得分:2)

这是因为您的查询返回了Orders个模型的列表,该列表没有name列,所以它不能表示此查询的结果。要查询模型中不可用的字段时,需要使用asArray()

ArrayHelper::map(
    \backend\models\Orders::find()
        ->select('orders.*,account_planLang.name as name')
        ->leftJoin('orders_props','`orders_props`.`order_id`= `orders`.`id`')
        ->leftJoin('account_plan','`orders_props`.`product_id`=`account_plan`.`id`')
        ->leftJoin('account_planLang','account_plan.id=account_planLang.plan_id')
        ->where('`orders`.`dt_end`<CURDATE() + INTERVAL 5 DAY AND `orders`.`dt_end`<CURDATE()')
        ->asArray() // <- this
        ->all(), 
    'id', 
    'name'
);

或在模型中添加name字段:

class Orders extends ActiveRecord {

    public $name;

    // ...

}

答案 1 :(得分:1)

我想没有必要使用 ArrayHepler :: map()。尝试这种方式:

Orders::find()
  ->select('account_planLang.name as name, table_name.id as id')
  ->leftJoin('orders_props','`orders_props`.`order_id`= `orders`.`id`')
  ->leftJoin('account_plan','`orders_props`.`product_id`=`account_plan`.`id`')
  ->leftJoin('account_planLang','account_plan.id=account_planLang.plan_id')
  ->where('`orders`.`dt_end`<CURDATE() + INTERVAL 5 DAY AND `orders`.`dt_end`<CURDATE()')
  ->indexBy('id')
  ->column();