2011-12-30 102 views
0

在我的应用程序中,用户可能有也可能没有配置文件。一个例子是:如果用户没有个人资料显示404

Array 
(
    [User] => Array 
     (
      [id] => 7 
      [username] => noprofile 
      [password] => 3b8cdb0c849f00f3634d9b29def1dac4e9235795 
      [email] => [email protected] 
      [status] => 0 
      [code] => 114a10ebb6ffe364805aa70cd44bee7c 
     ) 

    [Profile] => Array 
     (
      [id] => 
      [firstname] => 
      [lastname] => 
      [gender] => 
      [dob] => 
      [user_id] => 
     ) 

) 

在这里,用户noprofile在配置文件表中没有匹配的内容。

如何在发生这种情况时显示404?我试过了:

public function view ($username) 
{ 
    $this->Profile->User->recursive = 2; 

    $profile = $this->Profile->User->find('first', array( 
       'conditions' => array('User.username' => $username) 
      )); 

    if (empty($profile)) 
    { 
     echo 'echo1'; 
     throw new NotFoundException('No profile'); 
    } 
    else { 
     echo 'echo2'; 
    } 

    $this->set(compact('profile')); 
} 

但它没有显示404!我正在使用CakePHP 2.0。

这是因为它找到了用户,因此配置文件不是空的!如何检查配置文件为空?

+0

检查$ profile的值,并检查是否确实正在输入if语句并执行cakeError。 – Jrod 2011-12-30 16:02:35

+0

如何检查,因为我没有IDE来检查是否到达 – Cameron 2011-12-30 16:10:54

+0

您不需要IDE。在if语句之前打印/回显$ profile变量,然后在if语句中打印/回显一个字符串,如“嘿,我在IF语句中”。 – Jrod 2011-12-30 16:17:47

回答

1
if (empty($profile['Profile']['id'])) { 
    throw new NotFoundException(); 
} 

我希望有更好的方法来做到这一点,但是这是一个快速解决。如您所说,$profile将不会为空,因为找到了user

2

cakephp 2.0已经改变了显示错误的方式。现在你必须throw an exception。在你的情况,而不是:

$this->cakeError('error404'); 

你要做的:

throw new NotFoundException(); 

编辑: 在另一方面,你migth想要做你的查找查询使用JOIN(和递归-1),以便查询只有在他有配置文件时才能检索用户的信息。

希望这有助于

+0

我仍然可以访问该页面(即使在生产模式下) – Cameron 2011-12-30 15:55:47

+0

您是否尝试过在查找查询中使用连接?尝试调试您的代码。 'pr($ profile)''empty($ profile)'总是返回false,因为配置文件可能类似于'array(“name =>'','lastname'=>'',...) ' – pleasedontbelong 2011-12-30 16:44:10

相关问题