我刚刚创建了2个模型UsersModel和UserpicsModel并尝试获取两个记录,但它返回错误:调用非对象上的成员函数find()。
//UsersModel.php
class Users extends AppModel
{
public $hasMany = array(
'Userpics' => array(
'className' => 'Userpics'
)
);
}
//UserpicsMdoel.php
class Userpics extends AppModel
{
public $belongsTo = array(
'Users' => array(
'className' => 'Users',
'foreignKey' => 'uid'
)
);
}
//RecipesController.php
class RecipesController extends AppController {
public $uses =array('Users','Userpics');
public function view() {
$users = $this->Users->Userpics->find('all');
print('<pre>');
print_r($users);
print('<pre>');
exit;
}
}
答案 0 :(得分:0)
首先:你没有遵循蛋糕惯例:模型应该是单数而不是复数。
但实际问题是模型文件名称错误:如果您仍想使用您的约定,则Users
模型的名称应为Users.php
而不是UsersModel.php
Userpics
阅读this关于如何调试此类错误的有用答案。
但是如果您决定使用蛋糕命名约定(我强烈建议您这样做),请考虑执行以下操作:
//User.php (table users)
class User extends AppModel
{
....
}
//UserPic.php (table user_pics)
class UserPic extends AppModel
{
....
}
//RecipesController.php
class RecipesController extends AppController {
public $uses =array('User','UserPic');
public function view() {
$users = $this->User->UserPic->find('all');
print('<pre>');
print_r($users);
print('<pre>');
exit;
}
}
答案 1 :(得分:-1)
//UsersModel.php
class Users extends AppModel
{
public $hasMany = array(
'Userpics' => array(
'className' => 'Userpics',
'foreignKey' => 'uid'
)
);
}