dongxia2068 2019-05-21 10:13
浏览 71

有没有更好的方法来获取PHP中的多个对象?

Since a few weeks I use prepared statements in PHP with the fetch_object(className:: class). I really like this way because of the autocomplete in my controllers and in my view(Twig), but some times I need an inner join (One to many).

Now I do it like below. Luckily I have only a few results in the projects where I use this so the number of queries is low. But on a large result, this will create a lot of queries. To improve performance I store the $returnResult in apcu / Redis in the controller or save it in a JSON file when I can't use the other cache method.

My question is: can I do this on a better way to reduce the number of queries but still use the fetch_object(className:: class)

Thanks in advance for the help.

public function getAll()
  {
    // Create database connection
    $db = DB::connect();

    $stmt = $db->prepare("SELECT * FROM dataroom_category ORDER BY display_order");
    $stmt->execute();

    $returnResult   = [];
    $categoryResult = $stmt->get_result();

    $stmt2 = $db->prepare("SELECT * FROM dataroom_file WHERE dataroom_category_id = ? ORDER BY display_order");
    $stmt2->bind_param('i', $id);

    /** @var data $category */
    while ($category = $categoryResult->fetch_object(data::class)) {

      $id           = $category->getId();
      $stmt2->execute();
      $filesResult  = $stmt2->get_result();

      while ($file = $filesResult->fetch_object(DataroomFile::class)) {
        // Add the file to the setFiles array with $file->getid() as key
        $category->setFiles($file);
      }
      // I noticed by using mysqli_free_result the server used alot less memory at the end
      mysqli_free_result($filesResult);

      $returnResult[$category->getId()] = $category;
    }
    mysqli_free_result($categoryResult);
    $stmt2->close();
    $stmt->close();

    // Return the categories with the files for usage in the controller and view
    return $returnResult;
  }
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题
    • ¥20 win11修改中文用户名路径
    • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
    • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
    • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
    • ¥15 帮我写一个c++工程