php - Laravel 8:调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasMany::sync()
问题描述
我在 Laravel 8 中有一个项目,在这个项目中,它是一个电影存储,我在表和表之间有多对多关系。movies
actors
因此,为了调整这种关系,我将这些添加到模型中:
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_id
and movie_id
。但它会返回此错误:
> **BadMethodCallException** Call to undefined method
> Illuminate\Database\Eloquent\Relations\HasMany::sync()
那么这里出了什么问题呢?如何actor_movie
正确同步我的表?
我真的很感激你们的任何想法或建议......
提前致谢。
解决方案
public function movies()
{
return $this->belongsToMany(Movie::class);
}
电影.php:
public function actors()
{
return $this->belongsToMany(Actor::class);
}
在多对多关系中,我们必须使用belongsToMany()
推荐阅读
- java - Intellij 无法识别项目中的源目录
- javascript - 如何将使用 react-pdf 生成的 PDF 与现有 PDF 合并?(JS/node.js)
- c++ - 函数返回类型中的 decltype(auto) 不推导出 const 类型
- c - strncpy函数的循环看不懂
- mysql - AWS - RDS - MySQL - 内存不足
- sprite-kit - SpriteKit 对象不相互碰撞
- ios - URLSession 的 dataTask 未运行
- javascript - 我怎样才能使它根据输入产生不同的结果?
- html - (HTML/CSS) 背景在移动设备和桌面设备上的呈现方式不同
- vue.js - vue.js 显示数据彼此相邻而不是在