2011-11-09 47 views
2

我的操作:在項目控制器NULL,而不是在Yii的DAO SQL INSERT值:bindValue

修訂行動。在項目/瀏覽ajaxLink名爲/行動#

public function actionAddInterest() { 
      $itm= Item::model()->find("`ItemId` = :itm", array(':itm' => $_GET['ItemId'])); 
      $connection = yii::app()->db; 
      $sql1 = "INSERT INTO interest (UserId, ItemId) 
         VALUES(:usr, :itm)"; 
      $command=$connection->createCommand($sql1); 

      $command->bindValue(":usr", Yii::app()->user->id); 
      $command->bindValue(":itm", $itm); 
      $command->execute(); 
     } 

我也試過傾銷變量,並通過螢火...返回NULL這個響應。所以有些東西不適用於$ _GET。

$itm= Item::model()->find("`ItemId` = :itm", array(':itm' => $_GET['ItemId'])); 
var_dump($itm); 
die(); 

ORIGINAL

public function actionAddInterest() { 
     $model = new Item; 
     $connection = yii::app()->db; 
     $sql1 = "INSERT INTO interest (UserId, ItemId) 
        VALUES(:usr, :itm)"; 
     $command=$connection->createCommand($sql1); 

     $command->bindValue(":usr", Yii::app()->user->id); 
     $command->bindValue(":itm", $model->ItemId); 
     // $command->bindValue(":itm", $model->ItemId, PDO::PARAM_INT); //also tried 
     $command->execute(); 
    } 

No值被從$model->ItemId捕獲雖然,它返回一個NULL爲輸入。我在這裏錯過了什麼?

+0

$ model如何訪問?傳入一個函數? –

+0

Phill Pafford,編輯完整動作 – enfield

回答

2

感謝大家的幫助。

是完整這裏是解決方案..

我要補充

'data' => array('ItemId' => $model->ItemId), 

<?php 
    echo CHtml::ajaxLink(
    'Add Interest',   
    array('/item/addInterest'), 
    array(
     'data' => array('ItemId' => $model->ItemId), 
     'update'=>'#int_res' 
    ) 
); 
?> 

這是調用操作的ajaxLink。

0

您有 $ model = new Item; 所以它的新對象,它還沒有任何數據庫ID。您必須先添加值這個模型$

$model->label = "Abc"; 
$model->someMore = "val"; 

,並將其保存

if ($model->save()) { 
    //get ID 
    $itemId = app()->db->getLastInsertID(); 
} 

還是我失去了你的使命的東西嗎?

+0

看到評論我添加到VarioN的回覆 – enfield

0

如果你想從頁面上,你可以使用這種形式捕捉項目Id:

if (!isset($_POST['Item'])) 
    Yii::app()->end(); 

$model = new Item; 
$model->attributes = $_POST['Item']; 

... 

,比使用$模型 - >項目Id

但應該比你要求與提交表單這個動作按鈕。 因爲在另一種情況下不會有表單數據($ _POST ['Item'])。

+0

VarioN這只是完成其他[你幫助我的問題]的擴展(http://stackoverflow.com/questions/8023820/yii-按鈕來創建-DB-條目)。這裏沒有牽扯到ItemId的形式。它只需要與我正在查看的頁面相同的ItemId。此操作是項目控制器的一部分。我甚至嘗試過'$ itm = new Item(); ('ItemId =:itm',array(':itm'=> $ _ GET ['ItemId']​​));'但是仍然值出來NULL – enfield

+0

如果你沒有'在Item類中硬編碼的ItemId(如public ItemId = 1;),您應該通過GET或POST方法從請求中獲取它。 如果您選擇GET,您可以使用GET參數生成一個ajax鏈接。像。請確定您想從哪裏獲取ItemId?靜態地從代碼或動態地從用戶請求。 –