首页 > 解决方案 > 如何使用 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           
    }
}

标签: phpmysqllaravel

解决方案


假设两个表都已创建并且相同。

两种方式:1.如果两个表都连接到模型。使用雄辩:

Model1::query()->orderBy('id')->chunk('1000', function($rows) {
 foreach($rows as $row) {
//create() expects array
   Model2::create($row->toArray());
 }
});
  1. 如果它们是没有模型的表。使用查询生成器:
\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 崩溃。您可能希望将代码放入runSeeder 类的方法中。


推荐阅读