Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Como definir o valor de seleção múltipla do objeto array no yii2 durante a atualização


Este é um código de exemplo de uma classe de modelo Permit que tem um many to many relação com Activity através de PermitActivity (modelo de tabela dinâmica).

Atividade de classe modelo
public class Permit extends \yii\db\ActiveRecord {
    public $activities_ids;
    ...
    public function rules() {
        return [
            ...
            [['activities_ids'], 'safe'],
            ...
        ];
    }
    ...
    // Method called after record is saved, be it insert or update.
    public function afterSave($insert, $changedAttributes) {
        // If this is not a new record, unlink all records related through relationship 'activities'
        if(!$this->isNewRecord) {
            // We unlink all related records from the 'activities' relationship.
            $this->unlinkAll('activities', true);
            // NOTE: because this is a many to many relationship, we send 'true' as second parameter
            // so the records in the pivot table are deleted. However on a one to many relationship
            // if we send true, this method will delete the records on the related table. Because of this,
            // send false on one to many relationships if you don't want the related records deleted.
        }

        foreach($this->activities_ids as $activity_id) {
            // Find and link every model from the array of ids we got from the user.
            $activity = Activity::findOne($activity_id);
            $this->link('activities', $activity);
        }

        parent::afterSave($insert, $changedAttributes);
    }
    ...
    // Declare relationship with Activity through the pivot table permitActivity
    public function getActivities(){
        return $this->hasMany(Activitiy::className(), ['id' => 'activity_id'])
            ->viaTable('permitActivity',['permit_id' => 'id']);
    }
    ...
    public function afterFind(){
        parent::afterFind();
        $this->activities_id = ArrayHelper::getColumn($this->activities, 'id');
    }
}

Dessa forma, a classe model é a responsável por criar e atualizar o relacionamento usando a tabela dinâmica.

O mais importante é ter o método de relacionamento declarado corretamente.

Editar

Este é um exemplo da visualização usando kartikv\widgets\Select2 . Eu realmente não sei se dropDownList suporta seleção múltipla, no entanto Select2 tem tantos recursos úteis que eu costumo usá-lo sobre outras opções.
echo $form->field($model, 'activities')->widget(Select2::classname(), [
    'data' => $data,
    'options' => [
        'placeholder' => '...'
    ],
    'pluginOptions' => [
        'allowClear' => true,
        'multiple' => true,
    ],
]);