【问题标题】:Laravel eloquent: Update A Model And its RelationshipsLaravel 雄辩:更新模型及其关系
【发布时间】:2014-08-03 16:54:22
【问题描述】:

使用 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

有人可以帮帮我吗?

【问题讨论】:

  • 没有办法解决这个问题,但是你有没有尝试过这样的事情:$model->relationship->fill($data['relationship']); 然后push
  • 这就是我目前所做的,但我想知道是否有更优雅的方式来做到这一点:)
  • 没有其他方法,因为 Eloquent 目前不知道模型上的关系,直到您将它们称为动态属性、使用 load 方法加载、急切加载等(仅推送有效)与模型的relations 数组中存在的加载关系)

标签: php laravel model eloquent


【解决方案1】:

您可以实现observer pattern 来捕捉“更新” 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());
    }
}

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

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

请参阅laravel documentation 了解完整的活动列表。

【讨论】:

  • 非常感谢!那是(imo)解决这个问题的最佳方法
  • getAttributes() 方法不返回关系索引
【解决方案2】:

您可以尝试这样的事情,例如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了解更多详情。

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 2013-06-04
    • 2016-11-26
    • 1970-01-01
    • 2018-02-19
    • 2019-07-16
    • 2016-02-27
    • 1970-01-01
    相关资源
    最近更新 更多