关于同一个连接不同数据库之间的 Eloquent 关联查询

先来个妹子!

起因:由于不同业务被划分到不同的数据库,但是我在运营统计的时候却要将他们串起来统计比较麻烦,whereHas,withCount,hasManyThrough,hasOneThrough,都不好使,很多关联的表都不在一个数据库中。

于是我想到的解决办法如下:

数据库 a 有users 表
|  id | name  |
| ------------ | ------------ |
|  1 | xiaoming  |
|  2 | xiaohong  |

数据库 b 有topics 表
| id  | user_id  | data  |
| ------------ | ------------ | ------------ |
|  1 |  1 | test1  |
|  2 |  1 |  test2 |

再来看模型

class User extends Model
{
    protected $connection = 'a';

    public function Topic()
    {
        $this->hasMany(Topic::class);
    }
}

class Topic extends Model
{
    protected $connection = 'b';
}

尽管 User::with('Topic')->get(); 这肯定是没问题的,因为这会分为两次查询,会切换数据库

User::withCount('Topic')->get(); //这样就不行了
它会产生这样的sql语句。
select *,(select count(*) from topics where user_id = users.id ) as topic_count from users。
因为topics 在b 数据库中所以会报 table view not found

解决方案如下:
class Topic extends Model
{
    protected $connection = 'b';
    protected $table = 'b.topics'; //这里的b 必须是你的数据库名
}

User::withCount('Topic')->get(); 
它会产生这样的sql语句。
select *,(select count(*) from `b`.`topics` where `b`.`topics`.`user_id` = `users.id` ) as topic_count from `users`;

这只能解决同一个连接下的数据库。

不知道各位小伙伴还有没有更好的解决方案

本作品采用《CC 协议》,转载必须注明作者和本文链接
Mr.pan
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 3

我是来看妹子的

3年前 评论
pan_zoe (楼主) 3年前

哦吼,感谢伙计的文章,解决了我的问题

5个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!