我有两个表:用户和配置文件。用户可能有一个配置文件,配置文件必须有一个用户!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