Laravel eloquent:更新模型及其关系

2022-01-02 00:00:00 model php laravel eloquent

使用 eloquent 模型,您只需调用

With an eloquent model you can update data simply by calling

$model->update( $data );

但不幸的是,这不会更新关系.

如果你也想更新关系,你需要手动分配每个值并调用 push() 然后:

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.

我正在寻找类似的东西

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

有人可以帮我吗?

推荐答案

您可以实施观察者模式来捕捉更新"的 eloquent 事件.

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());
    }
}

当你调用 update 方法时,更新"事件将被触发,因此观察者将被触发.

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"
));

有关事件的完整列表,请参阅 laravel 文档.

See the laravel documentation for the full list of events.

相关文章