2011-12-30 39 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

相关问题