首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Laravel中循环多个DB连接

在Laravel中循环多个DB连接
EN

Stack Overflow用户
提问于 2022-10-14 11:33:53
回答 2查看 42关注 0票数 0

我正在总结来自不同表的列,每个列位于不同的数据库中。为8个连接中的每一个创建模型,并将它们添加到控制器中。

代码语言:javascript
复制
use App\Models\objectMapping1;
use App\Models\objectMapping2;
use App\Models\objectMapping3;
use App\Models\objectMapping4;
use App\Models\objectMapping5;
use App\Models\objectMapping6;
use App\Models\objectMapping7;
use App\Models\objectMapping8;

我的代码可以工作,但我对它不满意:

代码语言:javascript
复制
    $multyconnections1 = objectMapping1::where('userFK', '!=', 1)->where('del', 'no')->count();
    $multyconnections2 = objectMapping2::where('userFK', '!=', 1)->where('del', 'no')->count();
    $multyconnections3 = objectMapping3::where('userFK', '!=', 1)->where('del', 'no')->count();
    $multyconnections4 = objectMapping4::where('userFK', '!=', 1)->where('del', 'no')->count();
    $multyconnections5 = objectMapping5::where('userFK', '!=', 1)->where('del', 'no')->count();
    $multyconnections6 = objectMapping6::where('userFK', '!=', 1)->where('del', 'no')->count();
    $multyconnections7 = objectMapping7::where('userFK', '!=', 1)->where('del', 'no')->count();
    $multyconnections8 = objectMapping8::where('userFK', '!=', 1)->where('del', 'no')->count();
    
    $count = $multyconnections1 + $multyconnections2 + $multyconnections3 + $multyconnections4 + $multyconnections5 + $multyconnections6 + $multyconnections7 + $multyconnections8;
    print_r($count);

现在我试图为作业创建一个循环,但是我不知道如何指定数组中的模型.这就是我到目前为止所得到的。

代码语言:javascript
复制
$count = 0;
    $arrs = array('objectMapping1','objectMapping2', 'objectMapping3', 'objectMapping4', 'objectMapping5', 'objectMapping6', 'objectMapping7', 'objectMapping8' );
    foreach($arrs as $arr){
    $total = $arr::where('userFK', '!=', 1)->where('del', 'no')->count();
    
     $count+=$total;   
     print_r($count);
    }

我被告知错误“类"objectMapping1”找不到“

试图寻找不同的解决方案,但找到了none...any的想法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-14 11:58:49

尝试创建这样的对象数组

$arrs =数组(新objectMapping1、新objectMapping2、新objectMapping3、新objectMapping4、新objectMapping5、新objectMapping6、新objectMapping7、新objectMapping8);

票数 2
EN

Stack Overflow用户

发布于 2022-10-14 12:01:56

代码语言:javascript
复制
 function multyTable(){
        $count = 0;
        $arrs = array((new objectMapping1), (new objectMapping2),
         (new objectMapping3), (new objectMapping4), (new objectMapping5),
         (new objectMapping6), (new objectMapping7), (new objectMapping8()) );
        dump($arrs);

        foreach($arrs as $arr){
            $total = $arr::where('userFK', '!=', 1)->where('del', 'no')->join()->count();
        
            $count+=$total;   
        
        }
        print_r($count);

它的工作方式是那样的+格式化

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74068599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档