加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2021-07-06 05:19:14 所属栏目:大数据 来源: https://www.jb51.cc
导读:使用雄辩的模型,您只需通过调用即可更新数据 $model-update( $data ); 但不幸的是,这并没有更新关系. 如果您还想更新关系,则需要手动分配每个值并调用push()然后: $model-name = $data['name'];$model-relationship-description = $data['relationship']['d

使用雄辩的模型,您只需通过调用即可更新数据

$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

有人可以帮帮我吗?

解决方法:

您可以实现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());
    }
}

当您调用update方法时,将触发“更新”事件,因此将触发观察者.

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

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

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读