2012-03-02 9 views
1

私は1.3から2.0にCakePHPを移行しようとしています。そして今、特定のフィールドに値を挿入することに関する小さな問題に遭遇します。ここで私は、バージョン1.3で作られているコードです:今cakePHP 2.0のDBのフィールドに特定の値を保存する方法は?

function add() { 

    if(isset($_SESSION['User']['id'])){ 
     if(!empty($this->data)) { 
      if($this->Ad->save($this->data)){ 

       //saving the uID in table ads 
       $this->data['Ad']['uID'] = $_SESSION['User']['id']; 
       $this->data['Ad']['DatePosted'] = DboSource::expression('NOW()');  
       $this->data['Ad']['IP'] = $_SERVER['REMOTE_ADDR']; 
       $this->Ad->save($this->data, FALSE);      

       $this->Session->setFlash('The post was successfully added!'); 
       $this->redirect(array('action'=>'index')); 
      } 
      else{ 
      $this->Session->setFlash('The post was not saved. Please try again.', 'alert-message', array('class'=>'error')); 
      }    
     } 
    } 
    else{ 
     $this->Session->setFlash('You have to login first to access control panel'); 
     $this->redirect(array('controller'=>'users','action'=>'login')); 
    } 


    //for setting the category of advertisement 
    $adcats = $this->Ad->Adcat->find('list',array('fields'=>array('id','Description'))); 
    $this->set(compact('adcats')); 

    //for setting the type of advertisement 
    $adtyps = $this->Ad->Adtyp->find('list',array('fields'=>array('id','Description'))); 
    $this->set(compact('adtyps')); 

} 

が、ここでは、掲載日(DatePostedとして表して)私は(UIDとして表して)ユーザーIDを含めるしたい私のコードで、ユーザーのIPアドレスを入力します。

ここで私の質問は、私が以前に言及した3つのフィールドをどのように保存することができるかです。

答えて

0
if($this->Session->read('user_id')){  
    if($this->request->is('post')) { 

     $this->request->data('Ad.uID', $this->Session->read('user_id')); 
     $this->request->data('Ad.DatePosted', DboSource::expression('NOW()')); 
     $this->request->data('Ad.IP', $this->request->clientIp()); 
     // or $_SERVER['REMOTE_ADDR']; 

     if($this->Ad->save($this->request->data)){ 

      $this->Session->setFlash('The post was successfully added!'); 
      $this->redirect(array('action'=>'index')); 
     } 
     // and so on 

とする必要があります。あなたがnullのデフォルト値でdatetimecreatedと呼ばれるフィールドを持っている場合は、将来の参考のために

CakeRequest::data provides dot notation access to request data. Allows for reading and modification of request data, calls can be chained together as well

、ケーキは自動魔法のレコードの作成時刻を挿入します - おそらくDatePostedの必要性を排除します。

+0

ありがとうございます@あなたの応答のためのロス。しかし、別の質問があります。もし私が作成したDatePostedのフィールド名を変更し、それがケーキが自動的に作成された投稿時刻を追加すると言いましたが、このサンプルのコードのサンプルをもう一度聞かせてもらえますか?実際には、あなたが提供するコードは動作していますが、DatePostedだけが動作していないか、おそらく必要なコードが含まれている可能性があります。致命的なエラー:クラス 'DboSource'が見つからない – bowmeow

+0

そのエラーではわかりません - 恐らく2.0で変更された 'DboSource'を使って、それに関するドキュメントが見つかりません。自動マジックに関しては、 'created'、' modified'または 'updated'(または3つ全て)と呼ばれる、' datetime'とデフォルト値 'null'のフィールドがテーブルに必要です。ケーキは残りをする必要があります - コントローラコードを調整する必要はありません。参照してください。 – Ross

+0

助けてくれてありがとうRoss。 – bowmeow

関連する問題