Custom Pivot Table name giving error no such table:main

Viewed 137

Implementing many to many relationships with custom Pivot table name is giving error.

Service.php Model

class Service extends Model
{
  public function categories()
  {
      return $this->belongsToMany('App\ServiceCategory', 'category_service');
  }
}

ServiceCategory.php Model

class ServiceCategory extends Model
{
  public function services()
  {
      return $this->belongsToMany('App\Service', 'category_service');
  }
}

Table Names

  1. services
  2. service_categories
  3. category_service (Pivot Table Name)

Test

class RelationshipTest extends TestCase
{
  use RefreshDatabase;

    /** @test */
    public function a_service_can_belong_to_many_categories()
    {
      $service = factory(Service::class)->create();
      $category = factory(ServiceCategory::class)->create();

      $service->categories()->sync($category);

      $this->assertEquals(1, $service->first()->categories()->count());
      $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $service->categories);
    }
}

The test is giving this error.

PDOException: SQLSTATE[HY000]: General error: 1 no such table: main.categories

How to use custom pivot table name without getting this error.

1 Answers

I had the same error message and the issue came from my migration's foreign key constrains.

I forgot to override the default constrained() table name ("categories") to this:

Schema::create('category_service', function (Blueprint $table) {
    // ...
    $table->foreignId('category_id')->constrained('service_categories')->onDelete('cascade');
    // ..
});
Related