【发布时间】:2023-03-30 17:38:02
【问题描述】:
我在数据库中有一个表,用户不断添加数据,现在我从这个表中取出一些列并在第二个数据库('mysql2'):: 连接中进行插入,我使用 student_id 不允许它有一个复制记录 ne db2。但我的问题是有时INSERT会在db2中放入空数据,我不知道为什么会这样,但是在db1的表中数据被填充,而在db2中有时数据通过“”(空)。
使用 cronjob 每分钟执行一次,因为数据每时每刻都在更新
$data = DB::connection('mysql2')
->table('students')
->where('status', '=', 'Y')
->get();
foreach ($data as $key => $aStudent) {
// Check if student_id duplicated
$existing_data_in = DB::table('student')
->where("student_id", $aStudent->student_id)
->first();
if (! $existing_data_in) {
DB::connection('mysql')->table('student')->insert([
"first_name" =>$aStudent->first_name,
"last_name" =>$aStudent->last_name,
"age" =>$aStudent->age,
"student_id" =>$aStudent->student_id,
"created_at" =>$aStudent->created_at
]);
}
}
Log::info('Success, Data Updated');
或者我应该很少运行 cronjob 吗?我的问题是,当 table1 上的某些记录与数据一起归档时,当这条记录进入 table2 时,table2 上的记录为空。如果我在 table1 上检查相同的 student_id 没问题,但在 table2 上保存为空
我已经在 cronjob 上记录了我的查询,这就是我在表 2 上找到一个空字段时得到的结果。所以在这种情况下,表 1 上的姓氏填充了真正的姓氏,但表 2 上的插入为空这是查询(发生了什么)
[2022-01-19 14:16:17] local.INFO: select `student_id` `first_name`, `last_name`, `age`, `created_at` from `students` where `student_id` = ? limit 1 [421]
// this comes from query where i check for dublicated lines i think
[2022-01-19 14:16:17] local.INFO: select * from `student` where `student_id` = ? limit 1 [421]
[2022-01-19 14:16:17] local.INFO: insert into `student`
(`student_id`, `first_name`, `last_name`, `age`, `created_at`) values
(?, ?, ?, ?, ?)
["421","name","","38","2022-01-19 14:13:35"]
我使用的是 laravel 6.X 版本
【问题讨论】:
-
我不知道您的要求是什么,而是为上述要求创建 cron 作业,为什么在第一个表上插入用户数据后您不会添加相同的功能。只需要替换您已经在 cron 函数中执行的数据库连接。
-
如果我在表 sondazhes 中检查 studnet_id = '421',如果我在表 sondazhe 中检查 student_id = '421',我会看到姓氏已填写,我每 1 分钟插入带有作业的数据,last_name 为空这是个问题。如果我更换数据库连接有什么帮助?