关于同一个连接不同数据库之间的 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 协议》,转载必须注明作者和本文链接
我是来看妹子的
哦吼,感谢伙计的文章,解决了我的问题