Laravel 4 Eloquent模型观察者事件的顺序

时间:2014-04-30 23:58:35

标签: php laravel eloquent

根据http://laravel.com/docs/eloquent#model-observers,在创建新项目时会触发以下事件。 创建然后创建然后保存然后保存

然而,当我调用模型类时,事件正在被反射。在创建之前调用保存。

我的代码:

class TBone extends Eloquent {

    protected $table = 'bone';

    protected $primaryKey = 'id';

    protected $guarded = array('id');

}

观察者类:

class ObserverLeBone{

    public function creating($bone)
    {
        echo "creating\r\n";
    }

    public function saving($bone) 
    {
        echo "saving\r\n";
    }

    public function updating($bone) 
    {
        echo "updating\r\n";
    }
}

测试:

class EloquentTest extends TestCase {

    public function testObserver()
    {
       TBone::observe(new ObserverLeBone());
       $attributes = array('appreciatedAs' => 'Steak'); 
       TBone::create($attributes);
    }

}

运行测试用例时的输出:

saving
creating

所以我只是想知道为什么在创建事件之前触发了保存事件? 或者我错过了什么?

1 个答案:

答案 0 :(得分:3)

不确定它是否是错误或功能,但您是对的,根据代码,创建来电保存

public static function create(array $attributes)
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

保存触发事件:

public function save(array $options = array())
{
    $query = $this->newQueryWithDeleted();

    // If the "saving" event returns false we'll bail out of the save and return
    // false, indicating that the save failed. This gives an opportunities to
    // listeners to cancel save operations if validations fail or whatever.
    if ($this->fireModelEvent('saving') === false)
    {
        return false;
    }

            ....

在执行插入(创建)之前:

    else
    {
        $saved = $this->performInsert($query);
    }

激发创建事件

if ($this->fireModelEvent('creating') === false) return false;