2012-08-27 47 views
0

我有3個表在CakePHP的2應用程序:

用戶
用紙的user_id字段找到用戶的個人資料信息?

  • ID
  • 電子郵件

型材

  • USER_ID

論文

  • ID
  • 標題
  • USER_ID

我將顯示此:

------------------------------------------------------------------ 
| user->ID | profile -> name | paper -> ID | paper -> title | 
------------------------------------------------------------------ 
| 123 |  jack   |  12  |  test1  | 
------------------------------------------------------------------ 
| 125 |  jonn   |  15  |  mypaper | 
------------------------------------------------------------------ 
etc. 

也許用戶沒有任何紙張。
用戶擁有一個配置文件。
用戶有許多紙張。

我怎麼能在user_controller的操作中做到這一點?

回答

1

您只需要在相應的模型中指定模型關聯。將以下文件保存在app/Model文件夾中。

//User Model: User.php 
App::uses('AppModel', 'Model'); 
class User extends AppModel 
{ 
public $name = 'User'; 
public $useTable = 'users';  
public $primaryKey = 'id'; 
public $hasOne = array('Profile' => array(
              'className' => 'Profile', 
              'foreignKey' => 'user_id' 
             ) 
         ); 
public $hasMany = array('Paper' => array(
             'className' => 'Paper', 
             'foreignKey' => 'user_id' 
             ) 
         ); 
} 

//Profile Model: Profile.php 
App::uses('AppModel', 'Model'); 
class Profile extends AppModel 
{ 
public $name = 'Profile'; 
public $useTable = 'profiles';  
public $primaryKey = 'id'; 
public $belongsTo = array('User' => array(
              'className' => 'User', 
              'foreignKey' => 'user_id' 
              ) 
         ); 
} 

//Paper Model: Paper.php 
App::uses('AppModel', 'Model'); 
class Paper extends AppModel 
{ 
public $name = 'Paper'; 
public $useTable = 'papers';  
public $primaryKey = 'id'; 
public $belongsTo = array('User' => array(
              'className' => 'User', 
              'foreignKey' => 'user_id' 
              ) 
         ); 
} 

你可以簡單地找到通過一個單一的查詢其個人資料詳細信息以及用戶的詳細信息,以及所有紙張的信息:

$result = $this->User->find('all', array('conditions' => array())); 

如果您想通過本文的USER_ID找出用戶的配置文件的詳細信息,然後你應該寫如下:

$result = $this->User->Paper('all', array('conditions' => array('Paper.user_id' => $user_id), 
           'recursive' => '2')); 

可以使用檢查輸出:pr($result);die;

+0

謝謝@Arun,但$ this-> User-> Paper-> find(...)。但不工作。 – Chalist

+0

我測試這個,並有工作: $ this->用戶 - >找到(...)沒有'遞歸'=>'2',並有工作。 感謝您的答覆哥們。 – Chalist

+1

謝謝,它總是我的樂意幫助。 :) –

相關問題