doujian3401 2016-09-22 09:59
浏览 443

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?

  • 写回答

1条回答 默认 最新

  • dtng25909 2016-09-22 10:22
    关注

    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,
        ]
    ],
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法