Laravel - 多个数据库连接得到3个表平均(Laravel - multiple datab

2019-11-05 04:15发布

我有3个数据库

DB_1(学生表)

id | students
1  | 42

db_2(学生表)

id | students
1  | 31

db_3(学生表)

id | students
1  | 22

在我的控制,我怎么能只用一个模型(学生)获得所有学生的总平均。 和刚刚重写数据库连接。

Answer 1:

最重要的一位是在查询之前呼吁型号的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;
            }


文章来源: Laravel - multiple database connection get average from 3 tables