【问题标题】:Active records: Working with a db object活动记录:使用 db 对象
【发布时间】:2012-01-15 00:40:12
【问题描述】:

我希望能够通过一个查询选择多行。我想知道你是否可以这样做?

$teamsQuery = $this->db;

foreach( $teamids as $teamid )
$teamsQuery->where('teamid', $teamid);

$teamsQuery->get('team');

$teams = $teamsQuery->result();

print_r($teams);

【问题讨论】:

    标签: php database object


    【解决方案1】:

    根据定义,ActiveRecord 将数据库中的单行包装在一个对象中,并将业务和持久性逻辑附加到它。如果您想通过一个查询获取多行,请查看TableDataGateway

    在 TableDateGateway 中,您将有一个方法 findTeamsByIds,您将传递整个 ID 数组,然后在 SELECT … WHERE … IN 查询中获取它们。

    【讨论】:

      【解决方案2】:

      你可以试试这种功能

       /**
       * get all data from the table
       *
       * @param string $sql - mySQL query string
       *
       * @return data as associative array
       * */
      function getAll($sql) {
          $res = mysql_query($sql);
      
          if (!$res) {
              die(mysql_error());
          }
      
          // Convert to array
          $ret = array();
          while ($row = mysql_fetch_assoc($res)) {
              // Add to array
              $index = count($ret);
              $ret[$index] = $row;
          }
      
          return $ret;
      }
      

      【讨论】:

      • while 循环是干什么用的?它以关联数组的形式获取该行,然后将该行分配给 $ret[$index] 但由于 $index 始终是相同的数字,$ret 将仅包含最后返回的行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 2011-03-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多