簡體   English   中英

嵌套在zend框架2.2中的where子句

[英]nested where clause in zend framework 2.2

我需要這樣的查詢

SELECT tbl_leads . * , tbl_lead_category.vLeadCategoryName AS vLeadCategoryName, tbl_lead_category.vLeadCategoryIcon AS vLeadCategoryIcon, Concat( vFirst, ' ', vLast ) AS vFirst
FROM tbl_leads
LEFT JOIN tbl_lead_category ON tbl_lead_category.iLeadCategoryID = tbl_leads.iLeadCategoryID
LEFT JOIN tbl_user ON tbl_user.iUserID = tbl_leads.iUserID
WHERE (
tbl_leads.eDeleted = '0'
)
AND (
tbl_leads.iUserID = '1'
)
AND (
vCompanyName LIKE '%t%'
OR vCompanyUrl LIKE '%t%'
OR vPersonName LIKE '%t%'
OR vDesignationName LIKE '%t%'
OR vSkypeID LIKE '%t%'
OR vEmailID LIKE '%t%'
OR vPhoneNumber LIKE '%t%')

我的代碼就像:

public function fetchAll($data, $aColumns, $iUserID = "")
{
    $select = $this->tableGateway->getSql()->select();
    $select->columns(array('*'));
    $select->join('tbl_lead_category', 'tbl_lead_category.iLeadCategoryID = tbl_leads.iLeadCategoryID', array('vLeadCategoryName', 'vLeadCategoryIcon'), "LEFT")
            ->join('tbl_user', 'tbl_user.iUserID  = tbl_leads.iUserID',array("vFirst"=>new \Zend\Db\Sql\Predicate\Expression("Concat(vFirst,' ',vLast)")),"LEFT");

    $where = new \Zend\Db\Sql\Where();
    $where->NEST->equalTo('tbl_leads.eDeleted','0')->UNNEST; 

    if(isset($iUserID) && $iUserID != "")
        $where->AND->NEST->equalTo ('tbl_leads.iUserID', $iUserID)->UNNEST;

    // start for searching
    if (isset($data['sSearch']) && $data['sSearch'] != "") {
        for ($i = 0; $i < count($aColumns) - 1; $i++) {
                $where->OR->like($aColumns[$i], "%" . $data['sSearch'] . "%");
        }
    }

/*i have tried this, but its giving error: not nested*****
    if (isset($data['sSearch']) && $data['sSearch'] != "") {
    $where->AND->NEST;  
        for ($i = 0; $i < count($aColumns) - 1; $i++) {
                $where->OR->like($aColumns[$i], "%" . $data['sSearch'] . "%");
    // how can i get  parentheses to my where which i am searching  
        }
    $where->UNNEST;
    } ***************/
    $select->where($where);
    var_dump($select->getSqlString());
    $resultSet = $this->tableGateway->selectWith($select);
    return $resultSet;
}

如果我使用嵌套而且不能通過使用for循環和if語句創建它,如果我有這樣的自定義查詢,我怎么能進行查詢,沒有括號我的查詢沒有意義。

我認為追隨更好。 NEST將打開支架UNNEST將關閉支架

$where = new Sql\Where();
$where->NEST//start braket
->equalTo('col','someVal')
->OR
->equalTo('col','secondVal')
->UNNEST //close bracet

要添加表達式嵌套,您需要使用Predicate::nest() 這將是$where->nest() )。 返回的對象是PredicateSet ,它將自動嵌套在查詢中。

然后你需要做的就是遍歷它並添加你的表達式

$where = new \Zend\Db\Sql\Where();

$predicateSet = $where->nest(); // Returns a new 'predicate set'

if (isset($data['sSearch']) && ! empty($data['aSearch'])) {
  for($x = 0; $x < count($aColumns); $x++) {
    if ($x > 0) $predicateSet->or();

    $predicateSet->like($aColumns[$x], $search);
  }
}
$where->unnest();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM