我正在使用CakePHP 2.0。我有2个型号/控制器(类别/优惠券):
// File: Model/Coupon.php
// Table Name: coupons
class Coupon extends AppModel {
public $displayField = 'Coupon';
}
// File: Model/Category.php
// Table Name: categories
class Category extends AppModel {
public $displayField = 'Category';
}
// File: Controllers/CouponsController.php
class CouponsController extends AppController {
}
// File: Controllers/CategoriesController.php
class CategoriesController extends AppController {
}
// File: Controllers/AppController.php
class AppController extends Controller {
public $helpers = array('Html', 'Form');
public function beforeFilter() {
//$this->set('cat', $this->Category->find());
$this->set('cat', $this->Coupon->find());
}
}
我正在尝试为AppController中的default.ctp视图设置一个变量。当我将'cat'设置为:“$ this-> Coupon-> find()”时,它会返回一个我可以在视图中打印出来的数组。当我将'cat'设置为注释行“$ this-> Category-> find()”时,我收到以下错误:
致命错误:在......
中的非对象上调用成员函数find()我已经尝试过这个错误处理,但我似乎无法弄明白。我错过了什么吗?
答案 0 :(得分:1)
听起来您的模型在尝试访问之前未加载。您需要确保两个模型都加载到控制器中。您可以通过多种方式之一完成此操作。
// before the class declaration
App::uses('Category','Model');
App::uses('Coupon','Model');
// in the beforeFilter
$this->loadModel('Category');
$this->loadModel('Coupon');
// as a var in the controller
public $uses = array('Category','Coupon');