1 year ago

Get relational data of many to many relationship with multiple database connection

Posted 1 year ago by danielesposito
  • Laravel Version: 5.5.
  • PHP Version: ">=7.0.0",
  • Database Driver & Version: MySQL


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.


class User extends Authenticatable

    protected $connection = 'host1';

    public function tasks()
        return $this->belongsToMany(Task::class, 'task_users', 'user_id', 'task_id');


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);

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($taskId);

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.

Any Help out there? I will really appreciate any suggestions on how to solve this.

Please sign in or create an account to participate in this conversation.