【问题标题】:Static drupal 7 query to dynamic query静态drupal 7查询到动态查询
【发布时间】:2020-07-28 08:23:54
【问题描述】:

我需要取agent_name、count(id)、ifs_code、area_code。

当我使用静态查询时一切正常:

$result = db_query('SELECT agent_name, count(id) as count, ifs_code, area_code FROM declarations WHERE fisccode = :idno GROUP BY agent_name', array(':idno' => $fisccode))->fetchAll();

此查询的结果:

/report5.inc:82: array (size=1) 0 => object(stdClass)[10] public 'agent_name' => string 'GHEOLARIS S.A' (length=13) public 'count' => string '3' (length=1) public 'ifs_code' => string '02' (length=2) public 'area_code' => string '0110' (length=4)

但我不明白如何在动态查询中将 count(id) 作为计数

我试试这个:

$result = db_select('declarations', 'd')
      ->fields('d', array('agent_name', 'ifs_code', 'area_code'))
      ->addExpression('COUNT(id)', 'count') // I THINK I DO SOMETHING WRONG ON THIS LINE
      ->condition('fisccode', $fisccode)
      ->groupBy('agent_name')
      ->range($context['sandbox']['progress'], 10);
$result->execute()->featchAll();

addExpression 破坏了一切,在这一行之后 phpStorm 给我这个警告:Method 'condition' not found in string

在drupal日志中我有这个错误:Call to a member function condition() on string

请帮帮我!!!

【问题讨论】:

    标签: php mysql sql drupal drupal-7


    【解决方案1】:

    我认为问题在于并非所有数据库 API 函数都可以链接。请仔细阅读Database API Chaining 声明:

    无法链接的函数:

    • addExpression()
    • addField()
    • addJoin()
    • extend()
    • innerJoin()
    • join()
    • leftJoin()
    • rightJoin()

    您共享的错误也表明了这一点,因为在使用不返回数据库对象的addExpression() 后,condition() 出现错误。

    因此,对于您的动态查询,最好在分配给$result 之前准备一个$query 变量左右:

    $query = db_select('declarations', 'd');
    $query->fields('d', array('agent_name', 'ifs_code', 'area_code'));
    $query->addExpression('COUNT(id)', 'count');
    $query->condition('fisccode', $fisccode);
    ...
    $result = $query->execute()->featchAll();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-03
      • 2013-08-18
      • 2011-09-16
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      相关资源
      最近更新 更多