关于同一个连接不同数据库之间的 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
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

我是来看妹子的

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

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

1年前 评论

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