I have a many to many relationship between users and tenants. This is on a SQLite db. When I try to do a attach on either side of the relationship:
$user = User::where("id", 2)->firstOrFail();
$tenant = Tenant::where("id", 2)->firstOrFail();
$tenant->users()->attach($user);
// same with inverse.
$user = User::where("id", 2)->firstOrFail();
$user->tenants()->attach([2]);
I get this error:
SQLSTATE[HY000]: General error: 1 no such table: main. (Connection: sqlite, SQL: insert into "tenant_user" ("tenant_id", "user_id") values ( 2, 2))
This makes no sense. As if I copy and paste the query Eloquent is trying to run DIRECTLY FROM THE ERROR in my DB console it works perfectly fine:
main> insert into "tenant_user" ("tenant_id", "user_id") values (2, 2)
[2025-03-11 16:32:36] 1 row affected in 10 ms
So obviously the table exists. But doing it through eloquent makes it fail for some reason. Once the relationship is created I can query it without any issues. I can't detach it however.
Here is my Tenant class:
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
and my User class:
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Tenant::class);
}
and my migration for the intermediate tenant_user table:
public function up()
{
Schema::create(
'tenant_user',
function (Blueprint $table) {
$table->foreignIdFor(User::class)
->references('id')
->cascadeOnDelete()
->cascadeOnUpdate();
$table->foreignIdFor(Tenant::class)
->references('id')
->cascadeOnDelete()
->cascadeOnUpdate();
}
);
}
I do have the spatie permissions package with teams enabled where tenant is my teams table but I don't think that would mess anything up since spatie doesn't create this relationship.
Any ideas? I'm at a loss. Thanks!