Trying to define a many-to-many relation with a pivot model in Laravel 8

  eloquent--relationship, laravel, many-to-many, pivot

Trying this for hours now and I don’t see the error. I have a model ‘User’ and a model ‘Round’. I want to define a n:m-relation with a model ‘Flight’ as pivot model.

User.php

<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

use SpatieMediaLibraryHasMedia;
use SpatieMediaLibraryInteractsWithMedia;

use SpatieImageManipulations;
use SpatieMediaLibraryMediaCollectionsModelsMedia;

class User extends Authenticatable implements MustVerifyEmail, HasMedia
{

    use Notifiable;
    use InteractsWithMedia;

    /*
    .....
    */

    public function rounds() {
        return $this->belongsToMany(Round::class)->using(Flight::class);
    }

}

Round.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Round extends Model
{

    /* 
    .....
    */

    public function users() {
        return $this->belongsToMany(User::class)->using(Flight::class);
    }

}

Flight.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentRelationsPivot;

class Flight extends Pivot
{

    public $incrementing = true;

    /*
    .....
    */

}

I made several migrations and seeder.

RelationSeeder.php

<?php

namespace DatabaseSeeders;

use IlluminateDatabaseSeeder;
use AppModelsRound;

class RelationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        
        $round = Round::find(1);

        $round->users()->sync([1]);
        
    }
}

When running artisan migrate:refresh --seed all tables are created as expected, but the following error occurs on seeding

SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘tour.round_user’ doesn’t exist (SQL: select * from round_user where round_id = 1)

Obviously Laravel is looking for a standard named pivot-table and not for the desired flights-table.

I am using Laravel 8 in a Docker-Container with Sail.

Where is my mistake?

Source: Laravel

Leave a Reply