use*_*571 12 php model laravel eloquent
使用雄辩的模型,您只需通过调用即可更新数据
$model->update( $data );
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这并没有更新关系.
如果您还想更新关系,则需要手动分配每个值并调用push()然后:
$model->name = $data['name'];
$model->relationship->description = $data['relationship']['description'];
$model->push();
Run Code Online (Sandbox Code Playgroud)
通过这项工作,如果您要分配大量数据,它将变得一团糟.
我喜欢这样的事情
$model->push( $data ); // this should assign the data to the model like update() does but also for the relations of $model
Run Code Online (Sandbox Code Playgroud)
有人可以帮帮我吗?
Mar*_*s L 12
您可以实现观察者模式来捕获"更新"eloquent的事件.
首先,创建一个观察者类:
class RelationshipUpdateObserver {
public function updating($model) {
$data = $model->getAttributes();
$model->relationship->fill($data['relationship']);
$model->push();
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其分配给您的模型
class Client extends Eloquent {
public static function boot() {
parent::boot();
parent::observe(new RelationshipUpdateObserver());
}
}
Run Code Online (Sandbox Code Playgroud)
当您调用update方法时,将触发"更新"事件,因此将触发观察者.
$client->update(array(
"relationship" => array("foo" => "bar"),
"username" => "baz"
));
Run Code Online (Sandbox Code Playgroud)
有关完整的事件列表,请参阅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();
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以保存关系.您可以查看此答案以获取更多详细信息.
归档时间: |
|
查看次数: |
14688 次 |
最近记录: |