2014-04-25 62 views
2

有一張桌子「公寓」。這裏需要在Yii中創建一個查詢。怎麼做?如何在Yii中使用union 2創建查詢?

SQL查詢:

SELECT * 
FROM {{apartments}} 
WHERE agent_id = 4 
UNION 
SELECT * 
FROM {{apartments}} 
WHERE agent_id != 4 

在我cintroller

$arrSql[] = 'SELECT * FROM {{apartments}} WHERE agent_id=:agent_id'; 
$arrSql[] = 'SELECT * FROM {{apartments}} WHERE agent_id!=:agent_id'; 
$data = Apartments::model()->findAllBySql(implode(' UNION ', $arrSql), array(
    ':agent_id' => Yii::app()->user->id, 
    ':status' => Apartments::STATUS_REMOVED 
)); 

$dataProvider = new CArrayDataProvider($data); 

但不工作分頁和過濾在我的窗口小部件CGridList。

+1

您查詢是一樣'SELECT DISTINCT * FROM公寓;',不是嗎? –

+0

[yii框架,如何實現union sql]可能的重複(http://stackoverflow.com/questions/12127908/yii-framework-how-to-implement-union-sql) – Dinistro

+2

你想要什麼?你在做SELECT * FROM {{apartments}} – Sadikhasan

回答

5

我所知,您可以使用CDbCommand這樣的:

$apartments2 = Yii::app()->db->createCommand() 
    ->select("*") 
    ->from('apartments') 
    ->where('agent_id!=:agent_id', array(':agent_id'=>4)) 
    ->getText(); 

$apartments = Yii::app()->db->createCommand() 
    ->select("*") 
    ->from('apartments') 
    ->where('agent_id=:agent_id', array(':agent_id'=>4)) 
    ->union($apartments2) 
    ->queryRow(); 

你可以找到你的結果在$apartments作爲一個數組。

編輯:

,如果你想使用CActiveDataProvider,你需要使用CSqlDataProvider

$sql='SELECT * 
FROM {{apartments}} 
WHERE agent_id = 4 
UNION 
SELECT * 
FROM {{apartments}} 
WHERE agent_id != 4'; 

$dataProvider=new CSqlDataProvider($sql, array(
    'totalItemCount'=>$count, 
    'sort'=>array(
     'attributes'=>array(
      'agent_id', //and all other atributes with withc you want to sort 
     ), 
    ), 
    'pagination'=>array(
     'pageSize'=>10, 
    ), 
)); 
+0

好方法,但我怎麼能用CActiveDataProvider和CDbCriteria爲我的小部件CGridList實現它? – Vitaly

-1

它非常簡單

(SELECT * 
    FROM {{apartments}} 
    WHERE `agent_id` = '4') 
UNION ALL 
    (SELECT * 
    FROM {{apartments}} 
    WHERE `agent_id` <> '4') 

讓我知道這是否爲你工作..

+5

質量好的答案應該有更多的解釋。請用評論解釋您的解決方案。謝謝。 – Raptor

+0

這不是那麼簡單的大聲笑。 – Gogol