Laravel雄辩:更新一个模型及其关系 [英] Laravel eloquent: Update A Model And its Relationships
问题描述
$ model-> update($ data)来更新数据;
但不幸的是,这不会更新关系。
如果要更新关系,您将需要手动分配每个值,并调用 push()然后:
$ model-> name = $ data [ '名称'];
$ model-> relationship-> description = $ data ['relationship'] ['description'];
$ model-> push();
通过这个工作,如果你有很多数据要分配,这将会变得混乱。 >
我对某些类似
$ model-> push($数据); //这应该将数据分配给类似update()的模型,但也可以为$ model
<有人可以帮我吗?你可以实现来捕捉升级雄辩的事件。
首先,创建一个观察者类:
public $ update $($ model){
$ data = $ model-> getAttributes();
class RelationshipUpdateObserver {
$ model-> relationship-> fill($ data ['relationship']);
$ model-> push();
}
}
然后将其分配给您的模型
class Client扩展Eloquent {
public static function boot(){
parent :: boot();
parent :: observe(new RelationshipUpdateObserver());
}
}
当你调用update方法时,更新事件将被触发,所以观察者将被触发。
$ client-> update(array(
relationship=> array(foo=>bar),
username=>baz
));
请参阅 laravel文档的完整的事件列表。
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?
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.
这篇关于Laravel雄辩:更新一个模型及其关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!