0

I have two models, FirstModel and SecondModel.

FirstModel has the default database connection of mysql and SecondModel is on anotherMysql connection. So far, so good: say I try to do a one-to-many relationship, it works pretty well. But I need a many-to-many relationship, which is totally standard, but.

The pivot table firstModel_secondModel exists on the mysql connection (same as FirstModel).

Trying to query the many-to-many relationship like so: $firstModel->secondModels will result in an error, since is seeking the pivot table on the SecondModel's connection.

So my question is... Can I tell eloquent to seek the pivot table elsewhere? Is there a way to specify the pivot's connection ?

Jean-Philippe Murray
  • 1,208
  • 2
  • 12
  • 34
  • 1
    This may work https://stackoverflow.com/q/25142968/2188922 – Ersoy Jun 25 '20 at 17:44
  • 1
    @ersoy I am guilty of having read the linked thread, but not having scrolled down enough to a decent answer ! There is indeed something that seemed to have helped there (no more connection, but it returns as empty, so I must be doing something else wrong). Anyways, thanks for pointing it back to me, I'll write a proper answer when I figure it out entirely! – Jean-Philippe Murray Jun 25 '20 at 18:03

1 Answers1

1

As @ersoy pointed, there's an old thread about it where I could find the answer. (I just didn't scrolled long enough and didn't sort by votes, hence I discarded it in my first search).

The idea here is that we can specify which connection to use by using the dot notation of mysql.

Hence this:

public function FirstModel()
    {
        return $this->belongsToMany(SecondModel::class);
    }

just needs to become:

public function FirstModel()
    {
        $database = $this->getConnection()->getDatabaseName();
        return $this->belongsToMany(SecondModel::class, "$database.firstModel_secondModel");
    }

And it works !

Jean-Philippe Murray
  • 1,208
  • 2
  • 12
  • 34