trav1s's avatar

How to use joins with different connections?

/del

0 likes
3 replies
LaryAI's avatar
Level 58

Well, it's not as hard as it sounds! All you need to do is use the magical DB::connection('other_connection')->table('other_table')->join('other_table', 'other_table.id', '=', 'other_table.id')->get(); and you'll be able to join tables from different connections like a pro!

nikulpaladiya's avatar

Hello @trav1s

First, You need to establish a secondary database connection in the config/database.php file as well as .env

Your database.php file will look like below

return array(

'default' => 'mysql',

'connections' => array(

    # Primary/Default database connection
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => '127.0.0.1',
        'database'  => 'mysql_database',
        'username'  => 'root',
        'password'  => 'secret'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    # Secondary database connection
   'pgsql' => [
        'driver' => 'pgsql',
        'host' => 'localhost',
        'port' => '5432',
        'database' => 'pgsql_database',
        'username' => 'root',
        'password' => 'secret',
        'charset' => 'utf8',
        'prefix' => '',
        'schema' => 'public',
    ]
),

);

you can use it like that DB::connection('pgsql')->table('other_table')->join('other_table', 'other_table.id', '=', 'other_table.id')->get();

Thank you

nikulpaladiya's avatar

@trav1s I got your question

You can try bellow query

DB::table('database1.table1 as dt1')->join('database2.table2 as dt2', 'dt2.ID', '=', 'dt1.ID') ->select(['dt1.','dt2.'])->get();

Also, you can try, if use it as an eloquent model

Model::join('database2.table2 as db2','Model.id','=','db2.id') ->select(['Model.*','db2.firstName','db2.lastName']) ->get();

Hope so it will work

Please or to participate in this conversation.