当表中没有实际变化时,Laravel Eloquent会监听事件

时间:2015-02-10 18:26:50

标签: php laravel eloquent

我需要在模型中监听更新事件,但我需要对表格中不存在的一些变量进行建模。我是通过将公共变量添加到模型中来实现的,但是当我仅对这些变量进行更改时,假冒'属性我无法倾听。无论如何都要通过假冒'模型的属性,可以听取更新?

这是我的示例课程。

<?php

class School extends Eloquent {
    protected $table = 'schools';

    protected $fillable = array('name', 'type_id', 'city');
    protected $guarded = array('id');

    public $set_specialties;

    protected static function boot()
    {
        parent::boot();

        static::updating(function($model)
        {
            $data = array(
                'name' => $model->name,
                'type_id' => $model->type_id,
                'specialties' => $model->set_specialties,
                'city_id' => $model->city_id
            );

            $rules = array(
                'name' => 'required|min:3|max:50',
                'type_id' => 'required|min:1|max:300000',
                '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 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->set_specialties = $data['specialties'];
    $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' => 'It's updated successful!'));
}

1 个答案:

答案 0 :(得分:0)

您可以创建自定义事件,here官方文档!