0

I have 3 databases

db_1 (students table)

id | students
1  | 42

db_2 (students table)

id | students
1  | 31

db_3 (students table)

id | students
1  | 22

In my controller, how can i get the total average of all students by using only one model (Student). and by just overriding the database connection.

Beginner
  • 1,700
  • 4
  • 22
  • 42

1 Answers1

1

The most important bit is the setConnection() method called on Model before querying. Remember that using it this way you need all the connections defined in your config/database.php under connections.

class StudentsController extends Controller {
        const DB_COUNT = 3;
        private $students;
        public function __construct(Students $students) {
            $this->students = $students;
        }

        public function index(Request $request) {
            for ($i=0; $i<self::DB_COUNT; $i++) { //or foreach through config('database.connections', [])
               $this->students->setConnection('db_'.($i+1));
               $students[] = $this->students->find(1)->students;
            }
            //what is "totalAVG" ???
            $totalAvg = array_sum($students) / self::DB_COUNT;
        }
    }

Alternatively if we want to stick to particular connection names:

public function index(Request $request) {
                foreach (config('database.connections', []) as $connName => $params)
                   $this->students->setConnection($connName);
                   $students[] = $this->students->find(1)->students;
                }
                //what is "totalAVG" ???
                $totalAvg = !empty($students) ? array_sum($students) / count($students) : 0;
            }
jakub wrona
  • 2,212
  • 17
  • 17
  • sir what if the name of databases is like these olfu, sti, mja – Beginner Sep 03 '18 at 23:12
  • it's not the database name which matters - it's the connection name. In config/database.php under connections you define connection name and its parameters. Each connection may have the same database name on different host or different database name on same host etc... – jakub wrona Sep 03 '18 at 23:26
  • sorry i mean the connection name on this line $this->students->setConnection('db_'.($i+1)); what if they have different connection names like for example olfu, sti, mja – Beginner Sep 03 '18 at 23:28
  • then replace the for loop with foreach (config('database.connections', []) as $connName => $params) and do $this->students->setConnection($connName); – jakub wrona Sep 03 '18 at 23:32
  • edited the answer to provide the alternative approach – jakub wrona Sep 03 '18 at 23:36
  • sir https://stackoverflow.com/questions/52171438/laravel-cronjob-run-whats-inside-the-method?noredirect=1#comment91293504_52171438 – Beginner Sep 04 '18 at 18:00