2012-09-14 39 views
1

我試圖基於full_name進行搜索,這是first_name和last_name的連接,但我不斷收到錯誤。Yii:在模型中使用CDbCriteria與自定義變量

這是我的控制器是什麼樣子:

$criteria = new CDbCriteria; 
$criteria->addSearchCondition('full_name',$customer_search); 
$customers = Customer::model()->findAll($criteria); 

在我的客戶模型中,我有一個應該返回FULL_NAME的方法:

public function getFull_name() { 
    return $this->first_name.' '.$this->last_name; 
} 

但是,我得到這個錯誤:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'where clause'. The SQL statement executed was: SELECT * FROM `customer` `t` WHERE full_name LIKE :ycp0 

我需要能夠搜索first_name和last_name,我需要更改爲做這個工作?

+0

用戶是否要在'$ customer_search'中輸入全名或部件名?即你是否希望他們能夠搜索'John Smith'並返回所有'John Smiths',或者用戶是否要搜索'John'並且想要返回所有帶有姓氏或名字'John'的人? – Stu

+0

我希望他們輸入第一個或最後一個名字的一部分,並讓它返回結果。因此,如果他們進入'ev',它會拉起'史蒂夫史密斯'和'鮑勃史蒂文斯',例如... – ews2001

回答

1

您不能在查詢中使用「計算」​​列。您只需重寫條件,以便只檢查數據庫中物理存在的列。

既然你想找到的人在那裏部分要麼他們的第一個或最後一個名稱匹配,你將不得不括在百分號(見LIKE MySQL文檔),搜索詞和與OR指定第二個條件:

$criteria = new CDbCriteria; 
$criteria->addSearchCondition('first_name', $customer_search); 
$criteria->addSearchCondition('last_name', $customer_search, true, "OR"); 
$customers = Customer::model()->findAll($criteria); 
+0

你介意提供一個我需要做的例子嗎?我明白數據庫中不存在full_name列,那麼我需要做些什麼改變? – ews2001

+0

@ ews2001:請看看更新。 – Jon

+0

這個伎倆......謝謝你。順便說一句,我刪除了通配符,因爲它們在使用addSearchCondition()時默認添加。所以我的最終結果是:'$ criteria-> addSearchCondition('first_name',$ customer_search); $ criteria-> addSearchCondition('last_name',$ customer_search,true,'OR');' – ews2001