首页 > 解决方案 > 跨数据库连接中断

问题描述

描述:

有两个模型(菜单、服务)和两个不同的数据库,模型中设置了连接。当我获得具有(服务)关系的菜单模型时,它工作正常。但是当用于has(service)获取有服务的菜单时会显示 Base table or view not found: 1146 Table 'common.services' doesn't exist

它将在我的第一个数据库中查找

common 是我的第一个数据库名称,服务存储在第二个数据库中。

重现步骤:

在不同的数据库中创建两个模型获取menu关系has(service)以仅获取具有服务的菜单

标签: laraveleloquent

解决方案


文档

来自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.


推荐阅读