Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

php - Laravel eloquent: Update A Model And its Relationships

With an eloquent model you can update data simply by calling

$model->update( $data );

But unfortunately this does not update the relationships.

If you want to update the relationships too you will need to assign each value manually and call push() then:

$model->name = $data['name'];
$model->relationship->description = $data['relationship']['description'];
$model->push();

Althrough this works it will become a mess if you have a lot of data to assign.

I am looging for something like

$model->push( $data ); // this should assign the data to the model like update() does but also for the relations of $model

Can somebody please help me out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...