2012-07-07 155 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() { 
     // ... 
    } 
} 
相关问题