沃梦达 / 编程问答 / php问题 / 正文

Laravel eloquent:更新模型及其关系

Laravel eloquent: Update A Model And its Relationships(Laravel eloquent:更新模型及其关系)

本文介绍了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.

这篇关于Laravel eloquent:更新模型及其关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel eloquent:更新模型及其关系

基础教程推荐