使用Laravel Eloquent在同一服务器上的不同数据库中联接两个MySQL表 [英] Join two MySQL tables in different databases on the same server with Laravel Eloquent

查看:231
本文介绍了使用Laravel Eloquent在同一服务器上的不同数据库中联接两个MySQL表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个不同的数据库中有两个表.这两个数据库都托管在同一台AWS RDS服务器上.我有一个可以访问两个数据库的用户帐户. 我在config \ database.php中定义了两个不同的连接:

I have two tables in two different databases. Both databases are hosted on same AWS RDS server. I have one user account which can access both databases. I defined two different connections in config\database.php:

return array(
    'default' => 'mysql',
    'connections' => array(
        # Our primary database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'samehost',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'samehost',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

对于table1,我有两个模型,它们连接到database1table2,并且连接到database2.两个表都有一个列id.如何使用Eloquent模型将具有相同id的行的查询联接在一起?

I have two models for table1 with a connection to database1 and table2 with a connection to database2. Both tables have a column id. How to join queries with Eloquent models for the rows with the same id?

推荐答案

此解决方案对我有用:

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

这篇关于使用Laravel Eloquent在同一服务器上的不同数据库中联接两个MySQL表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆