Laravel eloquent: Update A Model And its Relationships

后端 未结 2 1176
终归单人心
终归单人心 2020-12-15 23:33

With an eloquent model you can update data simply by calling

$model->update( $data );

But unfortunately this does not update th

2条回答
  •  孤城傲影
    2020-12-15 23:46

    You can implement the observer pattern to catch the "updating" eloquent's event.

    First, create an observer class:

    class RelationshipUpdateObserver {
    
        public function updating($model) {
            $data = $model->getAttributes();
    
            $model->relationship->fill($data['relationship']);
    
            $model->push();
        }
    
    }
    

    Then assign it to your model

    class Client extends Eloquent {
    
        public static function boot() {
    
            parent::boot();
    
            parent::observe(new RelationshipUpdateObserver());
        }
    }
    

    And when you will call the update method, the "updating" event will be fired, so the observer will be triggered.

    $client->update(array(
      "relationship" => array("foo" => "bar"),
      "username" => "baz"
    ));
    

    See the laravel documentation for the full list of events.

提交回复
热议问题