繁体   English   中英

CakePHP查找两个表中匹配的记录

[英]CakePHP find record that matches in two tables

我有两个表:Users和Profiles。 用户可能具有个人资料,而个人资料必须具有用户!

这些表是:

用户: 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配置文件,因为用户可能没有配置文件。 例如管理员帐户

轮廓:

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) ));

谢谢

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

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

然后,您将直接获得如下的User模型:

$this->User->...

我可能是错的,但我认为您不可能执行$this->Profile->User

[编辑:]

在讨论了这一点之后,看来用户模型应该确实具有$hasOne='Profile';

因为它不强制执行配置文件,但是只要存在就从数据库获取它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM