Home > Software engineering >  Looping multyple DB connections in Laravel
Looping multyple DB connections in Laravel

Time:10-14

I am summing the columns from different tables each in a different database. Created the models for each of the 8 connections and added them to the controller.

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;

My code works but I am not satisfied with it:

    $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);
    

Now I'm trying to create a loop for the job, but I don't know how to specify the models in the array... that's what I've got so far.

$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);
    }

I am given the error "Class "objectMapping1" not found"

Tried searching for different solutions but found none...any ideas?

CodePudding user response:

Try creating array of objects like this

$arrs = array(new objectMapping1, new objectMapping2, new objectMapping3, new objectMapping4, new objectMapping5, new objectMapping6, new objectMapping7, new objectMapping8);

CodePudding user response:

 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);

It works like that formatting

  • Related