0

What is the Laravel syntax to join 2 tables from different databases in postgres?

For example:

database1 table column
join
database2 table column
1
  • What is your problem here? What you have already done? Commented Dec 20, 2019 at 7:23

1 Answer 1

1

You can do it like this:

Configure:

Define the config/database.php multiple databases' connection:

        'pg' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            ...
       ];
        'pg_2' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST_ONLINE', '127.0.0.1'),
            'port' => env('DB_PORT_ONLINE', '3306'),
            'database' => env('DB_DATABASE_ONLINE', 'forge'),
            'username' => env('DB_USERNAME_ONLINE', 'forge'),
       ];
       ...

And set connection in Model:

class Model1 extends Model 
{
    protected $connection = 'pg';
}
class Model2 extends Model
{
    protected $connection = 'pg_2';
}

Usage:

And you can easily get Eloquent or query builder from different databases:

Model2::join('database1_name.table AS table1', 'table1.id', '=', 'model2.table_id')
       ->where(...)
       ->select('model2.*', 'table1.column')
# OR
\DB::connection('pg_2')->table('model2')
                       ->join('database1_name.table AS table1', 'table1.id', '=', 'model2.table_id')
                       ->where(...)
                       ->select('model2.*', 'table1.column')
Sign up to request clarification or add additional context in comments.

2 Comments

can i use the same with DB:: instead of ModelFromDB1?
@GDP if your table not from the default database, you need to use DB::connection('your_connection')->... However, you need to configure the connection in your database.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.