【发布时间】:2012-01-30 14:55:51
【问题描述】:
我有两个表:Users 和 Profiles。用户可能有个人资料,而个人资料必须有用户!
这些表格是:
用户: ID 用户名 电子邮件 密码
个人资料: 名 姓 性别 出生日期 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 个人资料,因为该用户可能没有个人资料。例如管理员帐户
简介:
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)