Laravel eloquent:更新模型及其关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24200089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:38:24  来源:igfitidea点击:

Laravel eloquent: Update A Model And its Relationships

phplaravelmodeleloquent

提问by user3518571

With an eloquent model you can update data simply by calling

使用 eloquent 模型,您可以通过调用简单地更新数据

$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:

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

$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?

有人可以帮我吗?

回答by Marius L

You can implement the observer patternto 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.

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

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

See the laravel documentationfor the full list of events.

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

回答by The Alpha

You may try something like this, for example a Clientmodel and an Addressrelated model:

你可以尝试这样的事情,例如一个Client模型和一个Address相关的模型:

// Get the parent/Client model
$client = Client::with('address')->find($id);

// Fill and save both parent/Client and it's related model Address
$client->fill(array(...))->address->fill(array(...))->push();

There are other ways to save relation. You may check this answerfor more details.

还有其他方法可以保存关系。您可以查看此答案以获取更多详细信息。