dp610807 2013-09-23 12:47
浏览 39

在没有多少查询的情况下访问Redbean多对多条目?

I've got two tables, table1 and table2, connected via many-to-many. So far there is no problem, but I would get a server-collapse for using the code below in productive usage. Accessing the many-to-many-join generates far to much queries.

Is there some better way to access the data (without raw querys)?

Code:

<?php
$table1_entry = R::findAll('table1');
foreach($table1_entry as $table1)
{
    echo $table1->id;
    foreach($table1->sharedTable2 as $table2)
    {
        echo $table2->id;
    }
}
?>

Redbean Query-Log:

string(34) "SELECT * FROM `table1` -- keep-cache"
  [1] =>
  string(71) "SELECT * FROM `table2_table1` WHERE ( `table1_id`  IN ( ?)  )  -- keep-cache"
  [2] =>
  string(61) "SELECT * FROM `table2` WHERE ( `id`  IN ( 1)  )  -- keep-cache"
  [3] =>
  string(71) "SELECT * FROM `table2_table1` WHERE ( `table1_id`  IN ( ?)  )  -- keep-cache"
  [4] =>
  string(61) "SELECT * FROM `table2` WHERE ( `id`  IN ( 2)  )  -- keep-cache"
  [5] =>
  string(71) "SELECT * FROM `table2_table1` WHERE ( `table1_id`  IN ( ?)  )  -- keep-cache"
  [6] =>
  string(61) "SELECT * FROM `table2` WHERE ( `id`  IN ( 3)  )  -- keep-cache"
  [7] =>
  string(71) "SELECT * FROM `table2_table1` WHERE ( `table1_id`  IN ( ?)  )  -- keep-cache"
  [8] =>
  string(61) "SELECT * FROM `table2` WHERE ( `id`  IN ( 4)  )  -- keep-cache"
  [...]
  • 写回答

1条回答 默认 最新

  • doq1969 2013-09-23 18:19
    关注

    Solution:

    //Create some pages and ads
    list($ad1, $ad2) = R::dispense('ad', 2);
    list($page1, $page2, $page3) = R::dispense('page',3);
    $ad1->sharedPage = array($page1, $page2);
    $ad2->sharedPage[] = $page3;
    R::storeAll(array($ad1, $ad2));
    
    //to check
    R::debug(1);
    
    //Now given the ads 
    R::each(R::find('ad'), 'sharedPage|page',function($ad, $pages){
      foreach($pages as $page) echo "
     AD {$ad->id} -> PAGE {$page->id} ";
    });
    

    Note that in RedBeanPHP you have to use

    'sharedPage'=>'page' 
    

    instead of

    'sharedPage|page'):
    

    More details can be found here:

    http://www.redbeanphp.com/eager_loading

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大