Hello I'm having trouble setting up a simple HABTM in cakephp.
Please tell me what is wrong? I followed the documentation closely.
My controller (it's a REST service)
class UsersController extends AppController {
public $components = array('RequestHandler');
public function index() {
$this->set(array(
'users' => $this->User->find('all'),
'_serialize' => array('users')
));
}
}
My User.php model:
class User extends AppModel {
public $hasAndBelongsToMany = array(
'Sport' => array(
'className' => 'Sport',
'joinTable' => 'sports_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'sport_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'with' => ''
)
);
}
My Sport.php Model
class Sport extends AppModel{
public $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'sports_users',
'foreignKey' => 'sport_id',
'associationForeignKey' => 'user_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'with' => ''
)
);
}
And this is how my DB looks like:
The users table:
The sports table:
Finally the sports_users table:
Lastly this is the error I'm getting:
Fatal error: Call to a member function schema() on a non-object in C:\wamp\www\SportsAround\lib\Cake\Model\Model.php on line 3627
Full image:
So where did I got it wrong? Thank you
I solved it by changing
public $hasAndBelongsToMany = array(
'Sport' => array(
'className' => 'Sport',
'joinTable' => 'sports_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'sport_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'with' => ''
)
);
To
public $hasAndBelongsToMany = array('Sport');
And
public $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'sports_users',
'foreignKey' => 'sport_id',
'associationForeignKey' => 'user_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'with' => ''
)
);
To
public $hasAndBelongsToMany = array('User');
But I still don't understand why that solved it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.