Eloquent - 如何在没有观察者的情况下等到 create() 之后

Eloquent - How to wait until after create() without Observer

错误

Call to a member function media() on null

情景

我有几个相关的模型。我有一个 "Event" 模型。附加到此(通过 1 到 1)是画廊模型。附加到它(通过一对多)是一个 "Media" 模型。在事件的 "created" 观察者中,我正在尝试附加其画廊。我可以毫无问题地创建图库,但是当我尝试将媒体附加到它时,出现上述错误。

我的代码

if ($model->gallery === null) {
   $this->createGallery($model);
}

// product images or banner images
$file = Storage::put("public/event_images/", $image);
$file = str_replace("public/event_images/", "", $file);
$file = "/" . $file;

$model->gallery->media()->create([
    "path" => $file,
    "type" => "image"
]);

// The createGallery() function
private function createGallery($model)
{
    $model->gallery()->create();
}

所以我知道要解决这个问题,我必须 "wait" 直到图库创建完毕才能尝试访问其关系。但我不知道该怎么做。此代码在 运行 第二次运行时表明画廊确实已创建 - 只是在代码到达 media() 之前速度不够快。

PHP 是一种同步编程语言,因此您不可能必须等待某事完成。

问题是您已经加载了该关系,并且此加载的关系不会 re-validate 直到您再次加载它。这可以使用 load() function.

来完成

更改您的代码以像这样创建图库:

if ($model->gallery === null) {

    // Create the related model
    $this->createGallery($model);

    // Load the relation again
    $model->load('gallery');
}

我认为您可能需要在尝试访问其关系之前刷新模型。在尝试将图像附加到图库之前尝试 $model->refresh()。像

if ($model->gallery === null) {
   $this->createGallery($model);
   $model->refresh();
}

否则模型不会知道新创建的画廊。