Laravel-多个数据库连接从3个表中获取平均值 [英] Laravel - multiple database connection get average from 3 tables

查看:126
本文介绍了Laravel-多个数据库连接从3个表中获取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个数据库

db_1(学生桌)

id | students
1  | 42

db_2(学生桌)

id | students
1  | 31

db_3(学生桌)

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.

推荐答案

最重要的一点是在查询之前在Model上调用的 setConnection()方法.请记住,以这种方式使用它需要在连接下的 config/database.php 中定义的所有连接.

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

这篇关于Laravel-多个数据库连接从3个表中获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆