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
- services
- service_categories
- 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.