LARAVEL如何连接2个不同的数据库并加入不同服务器上的2个表?

I have 2 different databases and I want to inner join 2 tables in these databases.

I know that this is not the best practice but I need to find a way to do this with LARAVEL.

I can do this with plain PHP by opening 2 connectios. But I am looking for way to do this with laravel.

$users = DB::connection('mysql2')->select(...);'

Adding another connection is the solution but how I will use two databases in 2 different servers in 1 inner join query?

Since I image you are working with different entities, just specify the connection of each of them in the model by defining a protected $connection property with the name of the connection.

You can create a new connection by defining it in config/database.php.

Like this:

class Model_One extends Entity
{
    protected $connection = "database_one";

    [...]

class Model_Two extends Entity
{
    protected $connection = "database_two";

    [...]
'connections' => [

    'database_one' => [
        'driver'    => 'mysql',
        'host'      => env('DB_ONE_HOST', 'host_one'),
        'port'      => env('DB_ONE_PORT', 3306),
        'database'  => env('DB_ONE_DATABASE', 'database_one'),
        'username'  => env('DB_ONE_USERNAME', 'username'),
        'password'  => env('DB_ONE_PASSWORD', 'secret'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => env('DB_ONE_PREFIX', ''),
        'timezone'  => env('DB_ONE_TIMEZONE', '+00:00'),
        'strict'    => false,
    ],

    'database_two' => [
        'driver'    => 'mysql',
        'host'      => env('DB_TWO_HOST', 'host_two'),
        'port'      => env('DB_TWO_PORT', 3306),
        'database'  => env('DB_TWO_DATABASE', 'database_two'),
        'username'  => env('DB_TWO_USERNAME', 'homestead'),
        'password'  => env('DB_TWO_PASSWORD', 'secret'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => env('DB_TWO_PREFIX', ''),
        'timezone'  => env('DB_TWO_TIMEZONE', '+00:00'),
        'strict'    => false,
    ]
],