【问题标题】:CakePHP find record that matches in two tablesCakePHP 在两个表中查找匹配的记录
【发布时间】: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)

标签: php cakephp


【解决方案1】:

根据您的路线,您将使用 ProfilesController 中的“用户”模型。为此,您应该在class ProfilesController extends Controller 之后添加以下行:

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

然后你直接得到这样的用户模型:

$this->User->...

我可能错了,但我认为你不可能做到$this->Profile->User

[编辑:]

在讨论了这个之后,看来用户模型真的应该有$hasOne='Profile';

因为它不强制执行配置文件,而只是从数据库中获取它(如果它存在的话)。

【讨论】:

  • 好的,试过了,但在我看来我得到了错误:Undefined index: Profile [APP/View/Profiles/view.ctp, line 1] 在 OP 中发布了我的视图代码
  • @Cameron 没关系,因为索引已更改。只需debug($data) 并相应地修复您的视图
  • 对不起,我没有关注。索引有什么问题?
  • @Cameron 不,Cakephp 2.0 没有改变这一点。您是否尝试从 cakephp1.3 迁移,因为您可以从他们的 migration guide 中受益
  • 好的,将调试($data)粘贴到这里:chat.stackoverflow.com/rooms/6265/about-so-8680577
猜你喜欢
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多