Laravel雄辩:更新模型及其关系

时间:2014-06-13 07:39:43

标签: php laravel model eloquent

使用雄辩的模型,您只需拨打

即可更新数据
$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

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:11)

您可以实施observer pattern来抓住"更新"雄辩的事件。

首先,创建一个观察者类:

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());
    }
}

当您调用更新方法时,"更新"事件将被触发,因此将触发观察者。

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

有关完整的活动列表,请参阅laravel documentation

答案 1 :(得分:5)

你可以尝试这样的事情,例如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();

还有其他方法可以保存关系。您可以查看this answer了解更多详情。