alexanderhempel's avatar

Join query with another database connection model

I have the following SQL-Query and can not figure out a way to build this with Eloquent:

SELECT
db1.table.*,
db2.table.*,
from db1.table
LEFT JOIN db2.table
ON db2.table.id = db1.table.id;

Both databases live on the same server.

I have two models with different connections and i tried to do some with a hasOne Relation.

Model for db1:

  class ModelOne

  public function modelTwo()
  {
    return $this->hasOne('ModelTwo', 'id');
  }

Model for db2:

  class ModelTwo

  public function modelOne()
  {
    return $this->belongsTo('ModelOne');
  }

When i dump the ModelTwo method, i get a beautiful eloquent relation object. But i couldn't find a way to use all its power.

0 likes
3 replies
pmall's avatar

I don't think you can do this.

1 like
JarekTkaczyk's avatar
Level 53

@alexanderhempel @pmall

It's tricky, but can be achieved. However there are some limitations, that may lead to raw solutions anyway.

Here's what you need, assuming db1 is default:

// class ModelOne
  public function modelTwo()
  {
    return $this->hasOne('ModelTwo', 'id');
  }

//class ModelTwo
  protected $table = 'db2.model_two_table';

  public function modelOne()
  {
    return $this->belongsTo('ModelOne', 'id');
  }

// then
$model1 = ModelOne::with('modelTwo')->get();
$model1 = ModelOne::has('modelTwo')->first(); 
// and so on

Mind that you can't use prefix for you tables in the db config. Also, if you define non-default connections on one of the models, then you need to adjust $table for both.

You can also use different connections for each model and many features will work just like that, however you can't rely on the joins that Eloquent builds:

ModelOne::with('modelTwo')->get(); // works as expected - this is what you asked for
ModelOne::has('modelTwo')->get(); // error, no table found

of course unless you have the same schema, but then it's not what you wanted anyway.

1 like

Please or to participate in this conversation.