Home > Software design >  Laravel 8 pivot working only in 1 direction
Laravel 8 pivot working only in 1 direction

Time:11-06

I got a problem I have done model and migration for 3 tables: movies, actors and actor_movie (pivot)

when Im using from model Actor method movie() it working but don't work from Movie using actor()

enter image description here

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');
    }

}

movies migration:

public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

actor migration:

public function up()
    {
        Schema::create('actors', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

Pivot migration:

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();
        });

    }

CodePudding user response:

As said in the comments, you are running your tests in a Tinker console. Tinker console loads all your PHP files and dependencies on startup and keep them in memory.

For your code to be refreshed, you need to kill tinker and restart it

  • Related