我有兩個表:用戶和配置文件。用戶可能有一個配置文件,配置文件必須有一個用戶!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) ));
感謝
設置'$ hasOne'關係。這並不意味着你必須擁有一個檔案,但你只能擁有一個檔案。然後你可以通過關聯訪問數據('$ this-> User-> Profile') – Ross 2011-12-30 15:21:58