zoukankan      html  css  js  c++  java
  • laravel 框架下 使用mysql 批量添加数据

    **批量添加数据**

    `class Messages extends ChefModel {
    //
    protected $table = 'messages';
    
    // 批量添加 性能更好,推荐使用
    public static function batchAdd($data) {
    DB::table('messages')->insert($data);
    }
    
    
    }
    

      

    实测,每次添加5000条数据时,速度最快

    public function send($pushLog) {
    $ftype = $pushLog->ftype;
    $title = $pushLog->title;
    $content = $pushLog->content;
    $description = $pushLog->description;
    $isAll = $pushLog->is_all;
    
    $userIdArray = [];
    if ($isAll == 1) {
    $userIdArray = User::pluck("id");
    } else {
    $userIdArray = explode(",", $description);
    }
    $num = 5000; //分组,每次群发5000个用户,实测5000个速度最快
    $group = [];
    $created = Date("Y-m-d H:i:s", time());
    $updated = Date("Y-m-d H:i:s", time());
    Log::debug("groupdata start:" . Date("H:i:s", time()));
    for ($i = 0; $i < count($userIdArray); $i++) {
    $group[$i / $num][] = ['user_id' => $userIdArray[$i],
    'title' => $title,
    'remark' => $content,
    'ftype' => 3, //系统消息
    'created_at' => $created,
    'updated_at' => $updated];
    }
    Log::debug("groupdata finish:" . Date("H:i:s", time()));
    foreach ($group as $key => $data) {
    Messages::batchAdd($data);
    if ($isAll == 0) {
    UserProfile::whereIn("user_id", array_column($data, 'user_id'))->increment("system_count");
    }
    }
    if ($isAll == 1) {
    UserProfile::increment("system_count");
    }
    Log::debug("adddata finish:" . Date("H:i:s", time()));
    $pushLog->status = 1; // 发送成功
    $pushLog->success_users = count($userIdArray);
    $pushLog->updated_at = Date("Y-m-d H:i:s", time());
    $pushLog->save();
    }
    

      

  • 相关阅读:
    剑指offer——最小的K个数和数组中第K大的元素
    Leetcode刷题指南链接整理
    160. Intersection of Two Linked Lists
    100. Same Tree
    92. Reverse Linked List II
    94. Binary Tree Inorder Traversal
    79. Word Search
    78,90,Subsets,46,47,Permutations,39,40 DFS 大合集
    0x16 Tire之最大的异或对
    0x16 Tire
  • 原文地址:https://www.cnblogs.com/lianruihong/p/10566875.html
Copyright © 2011-2022 走看看