首页 > 解决方案 > Laravel 8:调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasMany::sync()

问题描述

我在 Laravel 8 中有一个项目,在这个项目中,它是一个电影存储,我在表和表之间有多对多关系。moviesactors

因此,为了调整这种关系,我将这些添加到模型中:

Actor.php

public function movies() {
    return $this->hasMany(Movie::class);
}

Movie.php

public function actors() {
    return $this->hasMany(Actor::class);
}

而作为数据透视表的迁移actor_movie在这里:

Schema::create('actor_movie', function (Blueprint $table) {
    $table->unsignedBigInteger('actor_id');
    $table->foreign('actor_id')->references('id')->on('actors')->onDelete('cascade');
    $table->unsignedBigInteger('movie_id');
    $table->foreign('movie_id')->references('id')->on('movies')->onDelete('cascade');
    $table->primary(['actor_id','movie_id']);
});

现在在我插入新电影的表单中,我添加了一个选择选项来从数据库中检索所有当前演员,因此我可以选择多个演员,如下所示:

<select name="actors[]" class="form-control" id="actor" multiple>
    @foreach(App\Models\Actor::all() as $actor)
        <option value="{{ $actor->id }}">{{ $actor->name }}</option>
    @endforeach
</select>

在 Controller 方法上:

public function store(Request $request) {
    $movie = new Movie();
    $movie->director_id = $request->director;
    $movie->name = $request->name;
    $movie->link = $request->link;
    $movie->year = $request->year;
    $movie->starred = $request->starred;
    $movie->watched = $request->watched;
    $movie->save();

    if(!is_null($movie)) {
        $imdb = new Imdb();
        $imdb->rate = $request->imdb;
        $imdb->movie_id = $movie->id;
        $imdb->save();
    }

   $movie->actors()->sync(request('actors'));
   return view('/admin/movies');

}

如您所见$movie->actors()->sync(request('actors'));,应该同步该表的actor_idand movie_id。但它会返回此错误:

> **BadMethodCallException** Call to undefined method
> Illuminate\Database\Eloquent\Relations\HasMany::sync()

那么这里出了什么问题呢?如何actor_movie正确同步我的表?

我真的很感激你们的任何想法或建议......

提前致谢。

标签: phplaravellaravel-8

解决方案


    public function movies()
    {
        return $this->belongsToMany(Movie::class);
    }

电影.php:

public function actors()
    {
        return $this->belongsToMany(Actor::class);
    }

在多对多关系中,我们必须使用belongsToMany()


推荐阅读