2011-12-30 71 views
0

我有兩個表:用戶和配置文件。用戶可能有一個配置文件,配置文件必須有一個用戶!CakePHP查找匹配兩個表的記錄

的表是:

用戶: ID 用戶名 電子郵件 密碼

概況: 姓 姓氏 性別 DOB USER_ID

因此,作爲您可以通過user_id鍵將配置文件錶鏈接返回給用戶

如何根據用戶的用戶名查看配置文件?

,因爲它需要拉兩個表中的信息......到目前爲止,我:

public function view ($username) 
{ 
    $profile = $this->Profile->find('first', array(
       'conditions' => array('User.username' => $username) 
      )); 

    if (empty($profile)) 
    { 
     $this->cakeError('error404'); 
    } 

    $this->set(compact('profile')); 
} 

,這是它的路線:

Router::connect('/people/:userName',array('controller'=>'profiles','action'=>'view'), 
    array(
     'userName'=>'[A-Za-z0-9\._-]+', 
     'pass'=>array('userName') 
    ) 
); 

而且這裏的型號:

用戶:

class User extends AppModel 
{ 
    var $name = 'User'; 
} 

我沒有指定用戶hasOne配置文件,因爲用戶可能沒有配置文件。 e.g管理員帳戶

簡介:

class Profile extends AppModel 
{ 
    var $name = 'Profile'; 

    var $belongsTo = 'User'; 
} 

,這裏是我的觀點:

<h1><?php echo $profile['Profile']['firstname']; ?> <?php echo $profile['Profile']['lastname']; ?></h1>

但需要一定的轉向,以得到它正確的。根據CakePHP 2.0的書,我可以做如下的事情:$this->User-Profile->但我不完全理解它,或者我怎麼在這裏使用它?

例如這會是正確的:

$profile = $this->Profile->User->find('first', array( 'conditions' => array('User.username' => $username) ));

感謝

+1

設置'$ hasOne'關係。這並不意味着你必須擁有一個檔案,但你只能擁有一個檔案。然後你可以通過關聯訪問數據('$ this-> User-> Profile') – Ross 2011-12-30 15:21:58

回答

1

根據你的路線,你要使用 '用戶' 模式從ProfilesController。對於這個工作,你應該class ProfilesController extends Controller後添加以下行:

public $uses = array('User','Profile');

然後,你直接在用戶模式是這樣的:

$this->User->...

我可能是錯的,但我不認爲你可能做$this->Profile->User

[編輯]

討論這個後,它出現在用戶模型要真有$hasOne='Profile';

因爲它不強制配置文件,但是從數據庫中只得到它,如果它曾經存在。

+0

好吧,但在我看來,我得到錯誤:'未定義索引:配置文件[APP/View/Profiles/view.ctp,第1行]'在OP – Cameron 2011-12-30 15:04:23

+0

@Cameron中發佈我的視圖代碼,因爲索引已經改變了。只需調試($ data)'並相應地修復您的視圖 – 2011-12-30 15:07:36

+0

對不起,我不關注。索引有什麼問題? – Cameron 2011-12-30 15:10:06

相關問題