2012-01-26 8 views
-2

コントローラーメソッドのモデルでデータにアクセスしようとしています。CakePHP 2.0のコントローラー内のモデルデータにアクセス

初心者のために、これらの2つの違いは何ですか?

$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>$id))); 

$this->set(compact('post')); 

$this->Post->id = $id; 

$this->data = $this->Post->read(); 

私はそうのようにログインしているユーザーに対してポストのためのuser_idを比較しようとしているよう:

if($this->Post->user_id != $this->Auth->user('id'))

が、それは動作しません。 (常にfalseを返します)... 2つのコードチャンクの違いは何ですか?上の行が正しく動作しないのはなぜですか?

答えて

1

これは私がなってしまったものです:

$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>Tiny::reverseTiny($id)))); 

     if ($this->request->is('post') || $this->request->is('put')) 
     { 
      $this->Post->id = $post['Post']['id']; 
      if ($this->Post->save($this->request->data)) 
      { 
       $this->Session->setFlash('Your post has been updated'); 
       $this->redirect(array('controller' => 'posts', 'action' => 'index')); 
      } 
      else 
      { 
       $this->Session->setFlash('Server broke!'); 
      } 
     } 
     else 
     { 
      if($post['Post']['user_id'] != $this->Auth->user('id')) 
      { 
       $this->Session->setFlash('Not yours!'); 
       $this->redirect(array('controller' => 'posts', 'action' => 'index')); 
      } 
      else 
      {    
       $this->request->data = $this->Post->read(null, $post['Post']['id']); 
      } 
     } 
1

テスト、それは「USERID」このコードを比較することができますかどうかを確認するために:

function index() { 

    $user_id = $this->data['Post']['user_id']; 
    if($user_id != $this->Auth->user('id')){ 
    //go 
    } 

} 
+0

認証にあなたのコントローラ内で呼び出すことを覚えています。var $コンポーネント=配列(「認証」); –

+0

問題は認証ではありません! '$ this-> Post-> user_id'の問題は有効なコードさえあるのでしょうか? cakePhp 2.0のコードの – Cameron

+0

は$ this-> request-> data = $ this-> post-> read(null、$ id)です。 –

0

find()read()間の違いがありますが、読み取りは、すべての関連するモデルデータを取得しにモデルのアクティブなレコードを設定します結果。 findはクエリ内のすべての関連するモデルデータを検索し、その結果を変数に代入します。

返されたデータの構造を明らかにするには、debug($this->data)を使用してください。ユーザーIDは$this->data['Post']['user_id']です。

+0

私の質問は、find()と '$ this-> Post-> idの違いは何ですか? = $ id; 'これは、渡されたIDに基づいて現在のエンティティを設定するためです。 – Cameron

+0

@Cameronこれは私の最初の段落アドレスです... Findはフェッチします。ここでは、読み込みがアクティブなモデルをフェッチして設定します。ドキュメントを読む:http://book.cakephp.org/1.3/ja/view/1017/Retrieving-Your-Data#read-1029 – Dunhamzzz

+0

いいえ!私は見つけると読むの違いを理解する!私の疑問は、IDを介して投稿を検索することと、モデルに対してidを設定することの違いは何ですか: '$ this-> Post-> id = $ id;' – Cameron

関連する問題