我正在制作一个用于更新学校和专业数据透视表的多选表单元素school_specialty
。问题是,当我只更改多选而不是其他输入或文本区域中的某些内容时,我无法侦听模型事件,因此无法同步school_specialty
表。但是当我填写任何其他输入时,它的效果很完美。这是我从刀片中的多选:
{{Form::select('specialties[]', $specialties_data, $school->specialties, array('multiple' => 'true', 'id' => 'multi-select'))}}
这是我的更新方法school controller
:
public function update($id)
{
$data = Input::only('name', 'type_id', 'description', 'info_specialties', 'contacts', 'specialties', 'financing_id', 'district_id', 'city_id');
$school = School::find($id);
$school->name = $data['name'];
$school->type_id = $data['type_id'];
$school->description = $data['description'];
$school->info_specialties = $data['info_specialties'];
$school->contacts = $data['contacts'];
$school->cover_photo = Input::file('cover_photo');
$school->set_specialties = $data['specialties'];
$school->financing_id = $data['financing_id'];
$school->set_district_id = $data['district_id'];
$school->city_id = $data['city_id'];
try {
$school->save();
} catch (ValidationException $errors) {
return Redirect::route('admin.schools.edit', array($id))
->withErrors($errors->getErrors())
->withInput();
}
return Redirect::route('admin.schools.edit', array($id))
->withErrors(array('mainSuccess' => 'School was created.'));
}
这是我的例子school model
:
<?php
class School extends Eloquent {
protected $table = 'schools';
protected $fillable = array('name', 'type_id', 'description', 'city');
protected $guarded = array('id');
protected $appends = array('specialties');
public $set_specialties;
public $set_district_id;
protected static function boot()
{
parent::boot();
static::updating(function($model)
{
$data = array(
'name' => $model->name,
'type_id' => $model->type_id,
'description' => $model->description,
'specialties' => $model->set_specialties,
'city_id' => $model->city_id
);
$rules = array(
'name' => 'required|min:3|max:50',
'type_id' => 'required|min:1|max:300000',
'description' => 'required|min:10',
'specialties' => 'required|array',
'city_id' => 'required|min:1|max:300000'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator->messages());
} else {
return true;
}
});
static::updated(function($model)
{
if ( $model->set_specialties != null )
{
$model->specialty()->sync($model->set_specialties);
}
});
}
public function specialty()
{
return $this->belongsToMany('Specialty', 'school_specialty');
}
}
?>