Laravel - How to Join 2 Tables from Different Db Connection

Join two MySQL tables in different databases on the same server with Laravel Eloquent

This solution worked for me:

->join('database2.table2 as db2','','=','')

Join two tables from different database of different server in laravel

You can do so easily with Eloquent models. It is not proper SQL joins but you can achieve relationship querying across multiple database or event servers.

  1. In your config/database.php file, declare as much connection as needed
  2. Create the models you want for each table
  3. Specify the $connection attribute in the models

For example:

class Model1 extends Model
public $connection = 'mysql_database';

public function model2()
return $this->belongsTo(Model2::class);

class Model2 extends Model
public $connection = 'postgre_database';

public function model1s()
return $this->hasMany(Model1::class);

You can then use the relations between those models as normal Eloquent relationship

Laravel join two tables in different databases

the answer that I wanted was:

$user=DB::table(DB::raw('sarida_test.user AS db1_tb1'))
->join(DB::raw(' AS db2_tb2'),'db1_tb1.Id','=','db2_tb2.user_id')

Laravel 4: Join tables from different database

You can do exactly that using the DB class:

$results = DB::select('select * from database1.users u1 LEFT JOIN database2.users u2 ON = WHERE = ?', array(5));

You can also use Fluent to build the query, which would look something like:

$users = DB::table('db1.users as db1')
->leftJoin('db2.users as db2', '', '=', '')
->where('', 5)

Related Topics

Leave a reply