laravel - 跨数据库连接中断
问题描述
- Laravel 版本:#.#.# 8.18.1
- PHP 版本:#.#.# 7.4
- 数据库驱动程序和版本:MySQL 5.7.32
描述:
有两个模型(菜单、服务)和两个不同的数据库,模型中设置了连接。当我获得具有(服务)关系的菜单模型时,它工作正常。但是当用于has(service)
获取有服务的菜单时会显示
Base table or view not found: 1146 Table 'common.services' doesn't exist
它将在我的第一个数据库中查找
common 是我的第一个数据库名称,服务存储在第二个数据库中。
重现步骤:
在不同的数据库中创建两个模型获取menu
关系has(service)
以仅获取具有服务的菜单
解决方案
文档
来自Laravel 文档:
Eloquent 目前不支持跨数据库查询关系存在。这些关系必须存在于同一个数据库中。
QueryBuilder VS 雄辩
什么原因导致成功检索with()
和失败has()
?
QueryBuilder 跨数据库
with() 已Illuminate\Database\Eloquent\Builder
在数组中实现并收集关系$eagerLoading
以加载查询。
关系尚未实现跨数据库功能
但是 has() 具有Illuminate\Database\Eloquent\Concerns\QueriesRelationships
特征并在Illuminate\Database\Eloquent\Relations\Relation
调用getRelationWithoutConstraints()
中采用:
/**
* Get the "has relation" base query instance.
*
* @param string $relation
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
protected function getRelationWithoutConstraints($relation)
{
return Relation::noConstraints(function () use ($relation) {
return $this->getModel()->{$relation}();
});
}
正如 PHPDoc 所说,它只是获取has relation的基本查询实例。它是一个简单的方法,只需基于查询(父查询)创建一个简单的基本查询并添加它。getModel()
该解决方案可以使用DB::raw
.
推荐阅读
- arduino - Arduino shield SIM900 不响应 AT 命令
- python - 如何根据 Python 中的条件创建结果组合矩阵?
- kotlin - Kotlin - 在 hashmap 上使用 apply 或 also 不能按预期工作
- facebook - 主域和子域不同的 Facebook 评论系统
- node.js - 护照认证超时
- javascript - 重新排序和过滤对象数组
- android - Ionic Android 支持的最低 Gradle 版本为 4.6。当前版本是 4.1
- scom - SCOM - 查看上次登录的用户
- vba - Excel VBA - 密码保护工作表
- javascript - 链接可观察对象 Angular 5 / Rxjs