Laravel 8 枢轴仅在 1 个方向上工作
Laravel 8 pivot working only in 1 direction
我遇到了一个问题我已经为 3 个表完成了模型和迁移:电影、演员和 actor_movie(数据透视表)
当我使用模型 Actor 方法 movie() 时它可以工作,但不能使用 actor() 从 Movie 中使用
class Movie extends Model
{
use HasFactory;
public function actors()
{
return $this->belongsToMany(Actor::class, 'actor_movie');
}
}
class Actor extends Model
{
use HasFactory;
public function movies()
{
return $this->belongsToMany(Movie::class, 'actor_movie');
}
}
电影迁移:
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
演员迁移:
public function up()
{
Schema::create('actors', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
枢轴迁移:
public function up()
{
Schema::create('actor_movie', function (Blueprint $table) {
$table->bigInteger('movie_id')->unsigned()->index();
$table->foreign('movie_id')->references('id')->on('movies')->onDelete('cascade');
$table->bigInteger('actor_id')->unsigned()->index();
$table->foreign('actor_id')->references('id')->on('actors')->onDelete('cascade');
$table->primary(['actor_id', 'movie_id']);
$table->timestamps();
});
}
如评论中所述,您正在 运行 Tinker 控制台中进行测试。
Tinker 控制台在启动时加载所有 PHP 文件和依赖项,并将它们保存在内存中。
要刷新您的代码,您需要杀死 tinker 并重新启动它
我遇到了一个问题我已经为 3 个表完成了模型和迁移:电影、演员和 actor_movie(数据透视表)
当我使用模型 Actor 方法 movie() 时它可以工作,但不能使用 actor() 从 Movie 中使用
class Movie extends Model
{
use HasFactory;
public function actors()
{
return $this->belongsToMany(Actor::class, 'actor_movie');
}
}
class Actor extends Model
{
use HasFactory;
public function movies()
{
return $this->belongsToMany(Movie::class, 'actor_movie');
}
}
电影迁移:
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
演员迁移:
public function up()
{
Schema::create('actors', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
枢轴迁移:
public function up()
{
Schema::create('actor_movie', function (Blueprint $table) {
$table->bigInteger('movie_id')->unsigned()->index();
$table->foreign('movie_id')->references('id')->on('movies')->onDelete('cascade');
$table->bigInteger('actor_id')->unsigned()->index();
$table->foreign('actor_id')->references('id')->on('actors')->onDelete('cascade');
$table->primary(['actor_id', 'movie_id']);
$table->timestamps();
});
}
如评论中所述,您正在 运行 Tinker 控制台中进行测试。 Tinker 控制台在启动时加载所有 PHP 文件和依赖项,并将它们保存在内存中。
要刷新您的代码,您需要杀死 tinker 并重新启动它