· 9 years ago · Dec 27, 2016, 05:40 AM
1$this->User->find('all',array(
2 'conditions' => array('User.id' => $this->Auth->user('id')),
3 'fields' => array('User.id','UserRole.id')
4));
5
6// UserRole.php
7class UserRole extends AppModel {
8 public $belongsTo = array(
9 'User' => array(
10 'className' => 'User',
11 'foreignKey' => 'user_id'
12 )
13 );
14}
15
16// User.php
17class User extends AppModel {
18 public $hasMany = array(
19 'UserRole' => array(
20 'className' => 'UserRole',
21 'foreignKey' => 'user_id',
22 'dependent' => false,
23 )
24 );
25}
26
27public $recursive = -1;
28
29CREATE TABLE IF NOT EXISTS `user_roles` (
30 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
31 `event_id` int(10) unsigned NOT NULL,
32 `role_id` int(10) unsigned NOT NULL,
33 `user_id` int(10) unsigned NOT NULL,
34 PRIMARY KEY (`id`)
35
36CREATE TABLE IF NOT EXISTS `users` (
37 `id` int(11) NOT NULL AUTO_INCREMENT,
38 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
39 `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
40 `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
41 `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
42 `created` datetime DEFAULT NULL,
43 `modified` datetime DEFAULT NULL,
44 PRIMARY KEY (`id`),
45 UNIQUE KEY `email` (`email`)
46
47Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UserRole.id' in 'field list'
48SQL Query: SELECT `User`.`id`, `UserRole`.`id` FROM `atlanta`.`users` AS `User` WHERE `User`.`id` = 5
49
50$this->User->find('all',array(
51 'conditions' => array('User.id' => $this->Auth->user('id')),
52 'contain' => array(
53 'UserRole' => array(
54 'fields'=>array('id')
55 )
56 ),
57 'fields' => array('id')
58));
59
60$this->User->find('all',array(
61 'conditions' => array('User.id' => $this->Auth->user('id')),
62 'fields' => array('User.id'), // UPDATE: unfortunately you cant specify associated models fields without behavior
63 'recursive' => 1
64));