2012-07-07 68 views
3

我有一個具有位置屬性的用戶表,並且想要創建一個模型函數來檢索附近的用戶(在給定的半徑內)。這裏是我的模型:將自定義函數添加到cakephp中的模型

 
    class User extends AppModel { 
     public function getNearbyUsers($id,$dist=10) { 
      return $this->query(...); 
     } 
    } 

這裏是我的控制器,我正在嘗試調用該函數:

 
    class UsersController extends AppController { 
     public function getNearbyUsers($id) { 
      ... 
      $this->User->getNearbyUsers($id) 
      ... 
     } 
    } 

但是這樣做的結果:PHP Fatal error: Call to a member function getNearbyUsers() on a non-object

我在做什麼錯?


編輯:沒關係,它不再抱怨了。但是它拋出了一個SQL錯誤,我的模型函數從來沒有被調用。在上的MySQL查詢日誌進行進一步的檢查我看到這一點:

 
    Query SHOW TABLES FROM `xxx` 
    Query getNearbyUsers 
    Quit 


似乎CakePHP會解釋$這個 - >用戶 - > getNearbyUsers作爲文字查詢。所以我的問題仍然存在:如何將自定義函數添加到Cake中的模型中?

+0

的代碼看起來是正確的。你有沒有清理'app/tmp/cache'中的緩存? – dhofstet 2012-07-07 09:52:09

+0

我有同樣的問題,直到cakePHP 1.3它與CakePHP 2.4.x(至少我測試)一起不可用。 – SaidbakR 2014-03-18 11:37:15

+0

你可以解決查詢問題。我面臨着同樣的挑戰@ – aWebDeveloper 2014-08-17 20:51:04

回答

4

http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html

雖然CakePHP的模型功能,應該把你帶到任何你需要去, 不要忘記,模型類是正義的:類,使您 寫你自己的方法或定義你自己的屬性。

處理數據保存和提取的任何操作最好是放置在模型類中的 。這個概念通常被稱爲 胖模型。

模型

class Example extends AppModel { 
    function getRecent() { 
     $conditions = array(
      'created BETWEEN (curdate() - interval 7 day) and (curdate() - interval 0 day)' 
     ); 

     return $this->find('all', compact('conditions')); 
    } 
} 

getRecent()方法現在可以在控制器內使用。

控制器

$recent = $this->Example->getRecent(); 
+1

正如你可以從我包括的代碼中看到,我幾乎遵循你發佈的內容:) – 2012-07-07 04:34:15

+0

現在doc條目無效(可能已被刪除),因爲鏈接只是重定向到模型文檔,沒有提到額外的方法。 – 2013-03-25 13:10:44

+0

@RaduMaris更新了鏈接。謝謝 (: – 2013-03-25 13:35:33

0

有需要在代碼中,否則您將獲得非對象錯誤幾個其他項目。

在App型號:

<?php 

class Get extends AppModel { 
    public function getRecent() { 
     // $conditions = array(
      // 'created BETWEEN (curdate() - interval 7 day)' . 
      // ' and (curdate() - interval 0 day))' 
     //); 
     // return $this->find('all', compact('conditions')); 
    } 
} 

在應用程序控制器,

?php 



class GetsController extends AppController { 

    public $uses = array('Get'); // Needed, or the error will appear. 

    public function Example() { 
     $this->Get->getRecent(); 
    } 
} 
0

有同樣的問題與蛋糕1.3,使用插件(模塊),即使我們有型號名稱在整個應用程序中獨一無二(某些型號名稱用於多個插件中)只有在我要求控制器的$uses陣列中的模型與它的插件一起使用時,它才能工作,如下所示:'Module1.A'

app/plugins/plugin1/controllers/a_controller。PHP:

class AController extends AppController { 

    // using simple array('A') worked fine for cake methods (find, query ...) 
    // but did not recognized the custom method 
    public $uses = array('Plugin1.A'); 

    public function Example() { 
     $this->A->customMethod(); 
    } 
} 

應用程序/插件/ plugin1 /模型/ a.php只會:

<?php 

class A extends AppModel { 
    public function customMethod() { 
     // ... 
    } 
} 
相關問題