使用自定义数据透视表名称实现多对多关系会出错。
Service.php型号
class Service extends Model
{
public function categories()
{
return $this->belongsToMany('AppServiceCategory', 'category_service');
}
}
ServiceCategory.php模型
class ServiceCategory extends Model
{
public function services()
{
return $this->belongsToMany('AppService', 'category_service');
}
}
表名
- 服务
- 服务类别
- category_service(数据透视表名称(
测试
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('IlluminateDatabaseEloquentCollection', $service->categories);
}
}
测试给出了这个错误。
PDOException: SQLSTATE[HY000]: General error: 1 no such table: main.categories
如何使用自定义数据透视表名称而不出现此错误。
我收到了同样的错误消息,问题来自我的迁移的外键约束。
我忘记将默认的constrained()
表名("categories"(重写为:
Schema::create('category_service', function (Blueprint $table) {
// ...
$table->foreignId('category_id')->constrained('service_categories')->onDelete('cascade');
// ..
});