Yii2:Saving 列表框多 select 字段到数据库

Yii2:Saving listbox multi-select field to db

我创建了一个列表框和相关功能,就像在我的模型中一样 Appointment.php

Appointment.php

中的验证规则及相关函数
public function rules()
    {
        return [            
            ['weekdays', 'validateWeekDays'],

        ];
    }

public static function getWeekdaysList()
        {
            return [
                'monday' => 'Monday',
                'tuesday' => 'Tuesday',
                'wednesday' => 'Wednesday',
                'thursday' => 'Thursday',
                'friday' => 'Friday',
                'saturday' => 'Saturday',
                'sunday' => 'Sunday',
            ];
        }
    public function validateWeekdays ($attribute, $params)
        {
            $label = '«' . $this->getAttributeLabel($attribute) . '»';

            // Checking if it's array first
            if (is_array(!$this->$attribute)) {    
                $this->addError($attribute, "$label must be array.");

                return;
            }

            $allowedWeekdays = array_keys(static::getWeekdayslist());

            // Checking if every selection is in list of allowed values
            foreach ($this->$attribute as $weekday) 
            {
                if (!in_array($weekday, $allowedWeekdays)) {
                    $this->addError($attribute, "$label - $weekday is not in allowed list");
                }
            }

然后在我的_form.php

<?= $form->field($model, 'weekdays')->listBox(app\models\Appointment::getWeekdaysList(), [
    'multiple' => true,
    'size' => 7,
]) ?> 

现在在保存表单时出现如下错误: 数据库异常 – yii\db\Exception

PDOStatement::bindValue() expects parameter 3 to be long, string given
Failed to prepare SQL: INSERT INTO `appointment` (`appointment_id`,
`appointment_date`, 
 `patient_detail_id`, `patient_name`, 
`priority`, `doctor_name`, `doctor_fee`, 
`discount`, `weekdays`, `total_amount`, 
`is_paid`, `hospital_commission`) VALUES 
(:qp0, :qp1, :qp2, :qp3, :qp4, :qp5, 
:qp6, :qp7, :qp8, :qp9, :qp10, :qp11)

我需要做什么来纠正这个错误。谢谢。

好的,我只需要一个功能就可以了。

public function beforeSave($insert)
        {       
        $weekday = implode(",", $this->weekdays);
        $this->weekdays = $weekday;
        return parent::beforeSave($insert);
        }

在控制器更新操作中,我添加了行

$model->weekdays = explode(',', $model->weekdays);

谢谢。

在将数组保存到数据库字段(应该是 VARCHAR)之前尝试序列化您的数组:

public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) 
    {
        $this->weekdays = serialize($this->weekdays);
        return true;
    }
}

然后在再次获取时反序列化:

public function afterFind()
{
    parent::afterFind();
    $this->weekdays = unserialize($this->weekdays);
}

并确保在呈现表单时再次使用数组。你可以用 yii\helpers\Json::encode()yii\helpers\Json::decode().

做同样的事情