2015-05-04 131 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