Laravel eloquent: Update A Model And its Relationships(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:更新模型及其关系
基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
