2012-10-17 133 views
1

我使用zend框架1.12。我有以下查询来运行。zend框架子查询

"SELECT name,(select count(*) from org_quote_template_items where org_quote_template_items.quote_template_id = org_quote_templates.`id`) as total_line_item FROM `org_quote_templates`" 

在我的模型文件中,我是这样创建的。以下是我的模型文件。

class default_Model_DbTable_QuoteTemplates extends Zend_Db_Table_Abstract 
{ 
    /** 
    * Name of the original db table 
    * 
    * @var string 
    */ 
    protected $_name = 'org_quote_templates'; 


    public function getAllTemplate($where){ 
     $select = $this->select();   
     $subquery = " (SELECT COUNT(*) FROM org_quote_template_items WHERE org_quote_template_items.quote_template_id = org_quote_templates.`id`)"; 

     $select->from(array($this), array('org_quote_templates.*','total_line_items' => new Zend_Db_Expr($subquery))); 

     $select = $select->where('organization_id = ?',$where['org_id']); 

     $adapter = new Zend_Paginator_Adapter_DbSelect($select); 
     $paginator = new Zend_Paginator($adapter); 
     $paginator->setItemCountPerPage(
       Zend_Registry::get('config')->paginator->general); 
     pr($adapter); 
     exit; 
    } 
} 

我在运行代码时出现跟随错误。 “异常'Zend_Db_Table_Select_Exception'带消息'Select query can not join with another table'”

请让我知道我该怎么办?

回答

4

。在你的要求时发生错误。你应该有:

$select = $this->select(); 
    $subquery = "(SELECT COUNT(*) FROM dtempls WHERE order_id = orders.id)"; 

    $select->from ($this, array (
     'id', 
     'total_line_items' => new Zend_Db_Expr ($subquery) 
    )); 
+0

好吧,最后我去加入表,但我的需要是,如果有可能写子查询,那么它会很好。 –

+0

看到我的更新。 - – akond

+0

谢谢@akond,这个作品:)。 –

1

我认为你必须使用setIntegrityCheck(false)来实现这一点。 Check this link

+0

我试过这一点stil得到错误,子查询造成一些问题。我没有找到任何答案如何在zend框架中的select语句中使用子查询! –

+0

在我的情况下,它的工作:) –

0

你可以试试这个方法在Zend的

$this->select() 
->setIntegrityCheck(false) 
->from(array('oqt' => 'org_quote_templates'),array('total_line_item')) 
->joinLeft(array('oqti' => 'org_quote_template_items'), 'oqti.quote_template_id = oqt.id', array(count(*) as count))