CakePHP中的find()方法无法正常工作,尝试搜索并解决。

时间:2014-10-19 11:01:51

标签: cakephp find

我刚刚学习cakePHP。我有一个CATEGORIES表和一个POSTS表。帖子有一个类别。所以在POSTS表中有一个category_id外键。

在我的模型中,我有这个代码的Category.php。

<?php
App::uses('AppModel', 'Model');
class Category extends AppModel {
// A hasMany association will allow us to fetch a category’s posts when we fetch a Category   record.

public $primaryKey = 'category_id';
public $hasOne = 'Post';

} ?&GT;

在我的Post.php中,我有类似的东西。

class Post extends AppModel {
   public $hasMany = array('Photo');
   public $primaryKey = 'post_id';
   public $belongsTo = array('User'); // 'Category',
   public $relatedImages;
   public $belongsTo = 'Category';

现在我的PostController.php中有

    $allCategories = $this->Category->find('list');
    $this->set('allCategories', $allCategories);

目标是从类别表中检索所有类别并将其显示在我的表单中。

但是我遇到了对非对象

上的成员函数find()的调用错误

我不确定这里发生了什么。我怎样才能找到这个?

非常感谢!

2 个答案:

答案 0 :(得分:2)

使用

$this->Post->Category->find('list'); 

因为你必须在帖子控制器中转到分类表至帖子当前。

答案 1 :(得分:1)

在您的帖子模型中尝试声明类别如下

public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id'
    )
    'Category' => array(
        'className' => 'Category',
        'foreignKey' => 'category_id'
    )
);