- Laravel Version: 5.5.
- PHP Version: ">=7.0.0",
- Database Driver & Version: MySQL
Description:
I'm working with multiple database connections that have different schema. host1 and host2. My default database connection is host2.
My project has two tables. users exist on host1 and tasks exists on host2.
There is a many to many relationships on both tables. Pivot table for this relationship is task_users which exist on host2.
My model files are here.
User.php
class User extends Authenticatable
{
protected $connection = 'host1';
public function tasks()
{
return $this->belongsToMany(Task::class, 'task_users', 'user_id', 'task_id');
}
}
Task.php
class Task extends Model
{
protected $connection = 'host2';
public function users()
{
return $this->belongsToMany(User::class, 'task_users', 'task_id', 'user_id');
}
}
Steps To Reproduce:
Here is what I'm trying to do
$task = Task::find($taskId);
$task->users;
With this model files, when I'm trying to get users of a task, I'm getting this error.
Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: the "task_user" relationship does not exist
But then if I do the inverse like this:
$user = User::find($userId);
$user->task;
everything goes fine.
I have almost spent too much time to resolve this. But didn't get anyway. I don't know either this is an issue in laravel, not supported or I'm doing in wrong way.