Yii2。 Model::loadMultipe。如何加载 class 字段?

Yii2. Model::loadMultipe. How to load class fields too?

如何使用 loadMultipe 不仅加载数据库属性,还加载字段?

我有这样一个模型

class Person extends ActiveRecord
{

    public $birthdate_month;

    public $birthdate_day;

    public $birthdate_year;

...

    public function rules()
    {
        return [
            ...
            [['birthdate_month', 'birthdate_day', 'birthdate_year'], 'integer'],
            [['birthdate_month', 'birthdate_day', 'birthdate_year'], 'required']
        ];
    }

// I store data as one DATA field in DB and than use such methods to show it to the user

    public function afterFind()
    {
        if (isset($this->birthdate)) {
            $date = Carbon::createFromFormat('Y-m-d', $this->birthdate); //just a data-manipulation library

            $this->birthdate_month = $date->month;
            $this->birthdate_day   = $date->day;
            $this->birthdate_year  = $date->year;
        }

        return parent::afterFind();
    }



    public function beforeValidate()
    {
        $date            = Carbon::create($this->birthdate_year, $this->birthdate_month, $this->birthdate_day); //just a data-manipulation library
        $this->birthdate = $date->toDateString();

        return parent::beforeValidate();
    }
}

还有这样的景色

<?php $form = ActiveForm::begin() ?>

<?php foreach ($children as $i => $child): ?> //there are multiple persons (children)

...

 <?=$form->field($child, '[]birthdate_month', [...])->dropDownList([
                    '1'  => 'January',
                    ...
                ])?>

...

<?php endforeach; ?>

...

<?=Html::submitButton('Save', ['class' => 'ui primary button big'])?>
...

<?php ActiveForm::end(); ?>

在控制器中

Person::loadMultiple($children, Yii::$app->request->post());

填充属性,但字段仍然为空。我需要它们,因为我用它来连接并在数据库中创建一个日期字段。如何加载它们?

您可以使用日期选择器小部件来设置您的生日日期,包括日、月和年,这个小部件是日历

试试这个

$formDetails = Yii::$app->request->post('Person', []);
foreach ($formDetails as $i => $value) 
{
  $model = new Person();
  $model->setAttributes($value);
  $models[] = $model;
}

应将迭代器添加到视图中传递的数组

 <?=$form->field($child, "[$i]birthdate_month", [...])->dropDownList([
                    '1'  => 'January',
                    ...
                ])?>