【问题标题】:Accessing Redbean many-to-many entries without many queries?在没有很多查询的情况下访问 Redbean 多对多条目?
【发布时间】:2013-09-28 08:57:08
【问题描述】:

我有两个表,table1table2,通过多对多连接。 到目前为止没有问题,但我会因为在生产使用中使用下面的代码而导致服务器崩溃。 访问多对多连接会产生很多查询。

是否有更好的方法来访问数据(无需原始查询)?

代码:

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

Redbean 查询日志:

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"
  [...]

【问题讨论】:

    标签: php sql redbean


    【解决方案1】:

    解决方案:

    //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 "\n AD {$ad->id} -> PAGE {$page->id} ";
    });
    

    注意,在 RedBeanPHP 中你必须使用

    'sharedPage'=>'page' 
    

    而不是

    'sharedPage|page'):
    

    更多细节可以在这里找到:

    http://www.redbeanphp.com/eager_loading

    【讨论】:

    • 也好不到哪里去......array(4) { [0] =&gt; "SELECT * FROM table1 WHERE word like "A%" [1] =&gt; "SELECT * FROM table2_table1 WHERE ( table1_id IN ( ?,?,?,?,?,?,?,[...])" [2] =&gt; "SELECT * FROM table2_table1 WHERE ( id IN ( 1,2,3,4,5,6,[...]" [3] =&gt; "SELECT * FROM table2 WHERE ( id IN ( 1,2,3,4,5,6,[...]"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    相关资源
    最近更新 更多