php - 如何使用 laravel 将一个表的内容传输到另一个数据库表
问题描述
我在同一台服务器上有两个数据库,我想使用 laravel 框架将一个表(posts)的内容传输到另一个数据库表(buss_posts)。
我更新我的问题
这是我在第一个数据库上的 post 表
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('post_name');
$table->text('post_content');
$table->timestamp();
});
这是我在第二个数据库上的 buss_post 表
Schema::create('buss_posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('post_name');
$table->text('post_content');
$table->timestamp();
});
这是我的控制器 BlogController
class BlogController extends Controller
{
public function run()
{
// how can I change between two tables at the different database
// as you know I am connecting with one database
}
}
解决方案
假设两个表都已创建并且相同。
两种方式:1.如果两个表都连接到模型。使用雄辩:
Model1::query()->orderBy('id')->chunk('1000', function($rows) {
foreach($rows as $row) {
//create() expects array
Model2::create($row->toArray());
}
});
- 如果它们是没有模型的表。使用查询生成器:
\DB::table('table1')->orderBy('id')->chunk('1000', function($rows) {
foreach($rows as $row) {
//convert object to array
\DB::table('table2')->insert(json_decode(json_encode($row), true));
}
});
可能需要一段时间才能完成,具体取决于行数。但它不会使块的系统 cos 崩溃。您可能希望将代码放入run
Seeder 类的方法中。
推荐阅读
- swift - 如何从数据选择器中设置选定的时间,然后根据用户选择的时间显示包含时间输出的表格?
- google-cloud-storage - 如何使用带有签名网址的 gcs-resumable-upload
- python - 无法测量列表中每个项目的频率
- android - MLKit 条形码阅读器是否解决了 Mobile Vision API 条形码扫描仪上存在的本机崩溃问题?
- apache-spark - PySpark:使用从另一个数据框中随机选择的主键创建一列
- oauth - 当 XHR 指定 withCredentials 时会发送哪些凭据?
- mono - 在 MONO 中更改函数的操作以不执行任何操作
- php - 转换日期函数语言
- c# - 如何将参数传递给按钮单击
- java - 如何在 myadapter 中启动新意图