Laravel 5.5 - "Call to a member function sync() on null" 错误

Laravel 5.5 - "Call to a member function sync() on null" Error

我正在尝试保存 post 图像。将图像保存或移动图像到上传目录没有问题。但是在 sync 部分,它给了我那个错误。

(我有三个 tables。posts,media 和 pivot table)

这是同步代码;

$media = Media::where('created_at', '>=', Carbon::now()->subSecond(10))->pluck('id');

$post->media()->sync($media, true);

媒体模型;

public function posts(){

    $this->belongsToMany('App\Post','media_post','image_id','post_id');
}

和Post型号

public function media() {

    $this->belongsToMany('App\Media','media_post','post_id','image_id');
}

有什么建议吗?

你不是return你的关系方法。这就是为什么。

public function media()
{
    $this->belongsToMany(...);
}

这就是你正在做的,它没有 return

$n = null;
$n->sync(); // Call to a member function sync() on null

function a() { }
a()->sync(); // Call to a member function sync() on null

这是PHP。你定义了一个没有 return 任何东西的方法,如果你调用它,你最终会得到一个 null