简体   繁体   English

Laravel插入/更新/删除

[英]Laravel Insert/Update/Delete

I currently have this code below, however when adding around 2000 rows this runs too slow due to being in an foreach loop. 我目前在下面有此代码,但是当添加约2000行时,由于处于foreach循环中,因此运行速度太慢。

foreach($tables as $key => $table) {

    $class_name = explode("\\", get_class($table[0]));
    $class_name = end($class_name);

    $moved = 'moved_' . $class_name;
    ${$moved} = [];

    foreach($table[0]->where('website_id', $website->id)->get() as $value) {
        $value->website_id = $live_website_id;
        $value->setAppends([]);
        $table[0]::on('live')->updateOrCreate([
            'id' => $value->id,
            'website_id' => $value->website_id
        ], $value->toArray());
        ${$moved}[] = $value->id;
    }

    // Remove deleted rows
    if ($table[1]) {
        $table[0]::on('live')->where([ 'website_id' => $live_website_id ])
            ->whereNotIn('id', ${$moved})
            ->delete();
    }
}

What is happening is basically users will add/update/delete data in a development server, then when they hit a button this data needs to be pushed into the live table, retaining the ID's as auto incremental id's on the live won't work due to look-up tables and multiple users launching data live at the same time. 发生的事情基本上是用户将在开发服务器中添加/更新/删除数据,然后当他们按下按钮时,该数据需要被推送到活动表中,保留该ID,因为实时的自动增量ID将无法使用查找表和多个用户同时实时启动数据。

What is the best way to do this? 做这个的最好方式是什么? Should I simply remove all the data in that table (there is a unique identifier for chunks of data) and then just insert? 我是否应该简单地删除该表中的所有数据(数据块有唯一的标识符)然后插入?

I think can do: 我认为可以做到:

  • You can create a temp table and fill just like your development server and just rename table to published table 您可以创建临时表并像开发服务器一样填充,只需将表重命名为已发布表
  • Use Job and background service(async queue) 使用作业和后台服务(异步队列)
  • You can set your db connection as singleton, because connecting multiple times can waste time 您可以将数据库连接设置为单例,因为多次连接会浪费时间
  • Can use some sql tools for example if use postgresql you can use Foreign Data Wrapper(fdw) to connect db to each other and update and create in a faster way! 可以使用某些sql工具,例如,如果使用postgresql,则可以使用Foreign Data Wrapper(fdw)将数据库彼此连接,并以更快的方式进行更新和创建!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM