1

我是 cakephp 的新手 ..实际上我有两个问题 .. 第一个是我在 AppController 中设置变量以便在 default.ctp 中使用它们。

public function beforeRender(){

    $id = $this->Auth->user('idUser');

    $this->loadModel('Userinfo');
    $data= $this->Userinfo->find('all',array(
        'conditions' => array('Userinfo.User_id' => $id)
    ));

    foreach($data as $d){
        $product_purchase = $d['Userinfo']['product_purchase'];
    }

    $this->set('userinfo',$product_purchase);
}

所以当我在我的 default.ctp 布局中使用变量时它工作正常.. 但问题是当我从应用程序注销时它会在我的登录页面上显示此错误

未定义变量:product_purchase

我究竟做错了什么?顺便说一句,我想在这里提到的是,在我的登录页面中,我没有很好地使用 default.ctp,我认为这与 dat 无关

第二个问题是我想为特定用户显示特定的菜单项......所以我在我的视图页面中这样做

<?php if ($userinfo == 1){ ?> 
  <li><a href="explorer.html" class="shortcut-medias" title="Media">Media</a> </li>
<?php }else{ //nothing }?>

userinfo 中的值为 2 .. 但如果不工作 .. 它仍在显示菜单

4

1 回答 1

1

变量product_purchase未初始化

如果之前的 find 调用没有结果,$product_purchase则不会定义变量,从而触发未定义变量错误。如果没有登录用户,就会出现这种情况:

public function beforeRender(){

    // will be null if there is no user
    $id = $this->Auth->user('idUser');

    // unnecessary find call if there is no user, returning no rows
    $this->loadModel('Userinfo');
    $data= $this->Userinfo->find('all',array(
        'conditions' => array('Userinfo.User_id' => $id)
    ));

    // will not enter this foreach loop as data is empty
    foreach($data as $d){
        $product_purchase = $d['Userinfo']['product_purchase'];
    }

    // $product_purchase is undefined.
    $this->set('userinfo',$product_purchase);
}

对于问题中的代码,只需提前初始化变量:

public function beforeRender(){
    $product_purchase = null;

$productcut_purchase 可能会被覆盖

请注意,如果此查询返回的数据不止一行:

foreach($data as $d){
    $product_purchase = $d['Userinfo']['product_purchase'];
}

$product_purchase变量将仅包含最后一行的值。

如果只有一个结果 - 使用适当的方法。不要使用find('all')- 使用find('first'). 或者考虑到只检索一个字段这一事实 - 直接使用以下field方法:

$product_purchase = $this->Userinfo->field(
    'product_purchase', 
    array('Userinfo.User_id' => $id))
);
于 2013-06-19T21:01:13.420 回答