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.
- In your
config/database.php
file, declare as much connection as needed - Create the models you want for each table
- 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
Calculate Size in Bytes of Json Payload Including It in the Json Payload in PHP
Remove Country Code from Phone Number
Download a Facebook Video (.Mp4) Via PHP
How to Store Values from Foreach Loop into an Array
How to Remove Query Part from $Request->All() in Laravel Framework
In Laravel How to Get Data in One Query from 3 Tables
Laravel 5.5 Error 500 in Cpanel Shared Hosting
Session Data Not Preserved After Redirection
How to Change Value of Select Options Based on Another Select Option Selected
Delete Digits After Two Decimal Points, Without Rounding the Value
How to Pass an Array Within a Query String
How to Get Values of Checkbox Array in Laravel 5