【发布时间】: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
在我的控制器中,如何仅使用一个模型(学生)来获得所有学生的总平均数。并且只需覆盖数据库连接。
【问题讨论】:
我有 3 个数据库
db_1(学生表)
id | students
1 | 42
db_2(学生表)
id | students
1 | 31
db_3(学生表)
id | students
1 | 22
在我的控制器中,如何仅使用一个模型(学生)来获得所有学生的总平均数。并且只需覆盖数据库连接。
【问题讨论】:
最重要的一点是在查询之前在 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;
}
【讨论】: