2015-05-04 111 views
1

我有两个表的用户和友谊,我已经创建了模型和Friendshipscontroller,但是一旦我尝试“添加”一个朋友得到一个错误,我错过了“add_friend”视图。CakePHP的友谊

下面是从Friendshipscontroller

function add_friend ($id){ 
    if(!empty($this->data)){ 
     $this->Friendship->Create(); 
     if($this->Friendship->save($this->data)){ 
      $this->Session->setFlash('Friendship Requested'); 
      $this->redirect(array('controller'=>'users','action'=>'profile')); 
     } 
    } 

我add_friend功能,这是我提到它在我看来

<?php echo 
$this->Html->link('Add as Friend', array('controller' => 'Friendships', 'action'=>'add_friend', h($user['User']['id']))); 

我不知道我做错了什么,所以我不知道在哪里解决这个问题。

回答

3

在方法这第一行:

if(!empty($this->data)){ 

被评估为“假”,因为在这 - $>数据没有数据。因此,该方法没有其他任何操作,并且标准CakePHP流继续进行。这意味着,呈现视图。

显然,由于$ this-> data是空的,所以你方法的大部分代码都是“错误的”。谁和谁之间的友谊? 假设你已经在处理验证,友好和用户之间的关系,像这样的工作:

function add_friend ($id){ 
if(!empty($id) && $this->Friendship->User->exists($id)){ 
    $this->Friendship->create(); 
    if($this->Friendship->save(array('user_id' => $id, 'requesteduser_id' => $this->Auth->user('id')))){ 
     $this->Session->setFlash('Friendship Requested'); 
     $this->redirect(array('controller'=>'users','action'=>'profile')); 
    } 
} 

}

希望它能帮助!

+0

错误:调用成员函数exists()在非对象上。我之前使用了exists(),没有任何问题。难道是我在这里写错了吗? –

+0

您的错误(可能)是由于您没有在友谊和用户之间设置关系。 当给你的答案,我假设: 1.您正在使用CakePHP V2.X 2.方法add_friend在FriendshipsController 3.关于成立友好用户(属于关联) 4.您之间已经使用身份验证进行身份验证。 如果您不清楚以上任何一点,我建议您深入了解cakephp文档及其教程:http://book.cakephp.org/2.0/en/tutorials-and-examples html的 – nigeon