【问题标题】:Laravel - multiple database connection get average from 3 tablesLaravel - 多个数据库连接从 3 个表中获取平均值
【发布时间】:2018-09-04 07:35:29
【问题描述】:

我有 3 个数据库

db_1(学生表)

id | students
1  | 42

db_2(学生表)

id | students
1  | 31

db_3(学生表)

id | students
1  | 22

在我的控制器中,如何仅使用一个模型(学生)来获得所有学生的总平均数。并且只需覆盖数据库连接。

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

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

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

    或者,如果我们想坚持特定的连接名称:

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

    【讨论】:

    • 先生,如果数据库的名称像这些 olfu、sti、mja 会怎样
    • 重要的不是数据库名称——而是连接名称。在连接下的 config/database.php 中,您定义连接名称及其参数。每个连接可能在不同主机上具有相同的数据库名称或在同一主机上具有不同的数据库名称等...
    • 对不起,我的意思是这一行的连接名称 $this->students->setConnection('db_'.($i+1));如果它们有不同的连接名称,例如 olfu、sti、mja,该怎么办
    • 然后用 foreach (config('database.connections', []) as $connName => $params) 替换 for 循环并执行 $this->students->setConnection($connName);
    • 编辑了答案以提供替代方法
    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2016-11-13
    • 2021-06-14
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2022-01-02
    相关资源
    最近更新 更多