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:

Model1::where('postID',$postID)
->join('database2.table2 as db2','Model1.id','=','db2.id')
->select(['Model1.*','db2.firstName','db2.lastName'])
->orderBy('score','desc')
->get();

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('task_flow.tickets 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 u1.id = u2.id WHERE u2.id = ?', array(5));

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

$users = DB::table('db1.users as db1')
->select('db1.*')
->leftJoin('db2.users as db2', 'db1.id', '=', 'db2.id')
->where('db2.id', 5)
->get();


Related Topics



Leave a reply



Submit