2

フォームからAJAX呼び出しを実行しようとしていますが、モデルにコントローラーメソッドを記述して、結果をフォームに返しています。Yii SQLステートメント、またはYiiコンテキストでのデータの取得/受け渡しは初めてです。誰かがこれを書き込もうとして私の論理を導き/修正できますか?

これは元のmysqlクエリです

"SELECT AVG(rate_syr_mh)FROM packaging_metrics WHERE country LIKE '" . mysql_real_escape_string($country)."'". "AND std_rate != 0 

「これはこれまでの私のコントローラーアクションです。ここで正しい方向に進んでいるかどうかはわかりません。パラメーター$countryは、特定の変更でフォームから送信されたフォーム入力である必要があります。

    public function countryRate($country)
{

$country_std_rate = Yii::app()->db->createCommand() 
    ->select('AVG(std_rate)') 
    ->from('packaging_metrics') 
    ->where(array('like', 'country', '%$country%'))
    ->queryRow();

    return $country_std_rate;


}

エントリがゼロにならないように、元のクエリの一部を追加するにはどうすればよいですか?

また、この方法でクエリを返すことで、AJAXによる取得で数値の結果を受け取り、別のフォームフィールドに入力できるようになりますか?

4

1 に答える 1

1

How do I add the portion of my original query to avoid zero entries?

Answer

Look into how the query should be specified for CDbCommand's where(), the operator with the lowest mysql precedence (but ofcourse according to your sql), should be specified first in the list:

array(operator, operand1, operand2, ...),

In other words the evaluation of the where conditions occur in preorder, hence you specify the operators in a kind of prefix notation.

For example if you have:

Where (somecolumn like %somevalue%) AND (somecolumn!=somevalue)

you write it as:

AND (somecolumn!=somevalue) (like (somecolumn %somevalue%))

So this translates to:

->where(array('and','std_rate!=0', array('like', 'country', '%'.$country.'%')))

This can actually be better understood by checking the source code of CDBCommand, specifically the processConditions function.


Also will returning the query in this fashion allow retrieval by AJAX to recieve the number result to be put into another form field?

Answer: Nope.

To return ajax data you should be echoing your output. Additionally you can use CJSON::encode() to json encode your return values:

echo CJSON::encode($country_std_rate); // instead of return $country_std_rate
Yii::app->end(); // this is also useful in most situations, almost forgot to add! 

Note:

  1. '%$country%' will not work, but '%'.$country.'%' will.

  2. preorder and prefix notation are my understanding of the evaluation, not sure if the yii team intended it to be that exactly!

于 2012-07-17T22:57:02.007 に答える