[英]Laravel eloquent: Update A Model And its Relationships
使用雄辯的模型,您只需通過調用即可更新數據
$model->update( $data );
但不幸的是,這並沒有更新關系。
如果您還想更新關系,則需要手動分配每個值並調用push()然后:
$model->name = $data['name'];
$model->relationship->description = $data['relationship']['description'];
$model->push();
通過這項工作,如果您要分配大量數據,它將變得一團糟。
我喜歡這樣的事情
$model->push( $data ); // this should assign the data to the model like update() does but also for the relations of $model
有人可以幫幫我嗎?
您可以實現觀察者模式來捕獲“更新”eloquent的事件。
首先,創建一個觀察者類:
class RelationshipUpdateObserver {
public function updating($model) {
$data = $model->getAttributes();
$model->relationship->fill($data['relationship']);
$model->push();
}
}
然后將其分配給您的模型
class Client extends Eloquent {
public static function boot() {
parent::boot();
parent::observe(new RelationshipUpdateObserver());
}
}
當您調用update方法時,將觸發“更新”事件,因此將觸發觀察者。
$client->update(array(
"relationship" => array("foo" => "bar"),
"username" => "baz"
));
有關完整的事件列表,請參閱laravel文檔 。
您可以嘗試這樣的方法,例如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();
還有其他方法可以保存關系。 您可以查看此答案以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.