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

Php Laravel雄辩:更新模型及其关系,php,laravel,model,eloquent,Php,Laravel,Model,Eloquent,使用雄辩的模型,您只需调用 $model->update( $data ); 但不幸的是,这不会更新关系。 如果您也想更新关系,则需要手动分配每个值,然后调用: 尽管如此,如果你有很多数据要分配,它会变得一团糟 我渴望得到像这样的东西 $model->push( $data ); // this should assign the data to the model like update() does but also for the relations of $model 谁

使用雄辩的模型,您只需调用

$model->update( $data );
但不幸的是,这不会更新关系。

如果您也想更新关系,则需要手动分配每个值,然后调用:

尽管如此,如果你有很多数据要分配,它会变得一团糟

我渴望得到像这样的东西

$model->push( $data ); // this should assign the data to the model like update() does but also for the relations of $model

谁能帮帮我吗

您可以尝试类似的方法,例如
客户端
模型和
地址
相关模型:

// 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();
还有其他保存关系的方法。您可以查看更多详细信息。

您可以实现以捕获“更新”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方法时,将触发“update”事件,因此将触发观察者

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

有关事件的完整列表,请参阅。

没有此方法,但您是否尝试过类似的方法:
$model->relationship->fill($data['relationship')
然后
推送
?这就是我目前所做的,但我想知道是否有一种更优雅的方式来这样做:)没有其他方式,因为Eloquent目前不知道模型上的关系,直到您将它们称为动态属性、使用
加载
方法加载、急切加载等。(push仅适用于模型的
关系
数组中存在的已加载关系)非常感谢!也就是说(imo)此问题的最佳解决方案GetAttributes()方法不返回关系索引
$client->update(array(
  "relationship" => array("foo" => "bar"),
  "username" => "baz"
));