how to get cakephp recursive data - cakephp
CREATE TABLE IF NOT EXISTS `employees` (
`employees_id` int(11) NOT NULL AUTO_INCREMENT,
`employees_firstname` varchar(100) DEFAULT NULL,
`employees_middlename` varchar(45) DEFAULT NULL,
`employees_lastname` varchar(100) DEFAULT NULL,
`employee_gender` enum('M','F') NOT NULL,
`employees_dob` date DEFAULT NULL,
`employees_emailaddress` varchar(255) DEFAULT NULL,
`employees_password` varchar(45) DEFAULT NULL,
`employees_datejoined` date DEFAULT NULL,
`employees_code` varchar(45) DEFAULT NULL,
`employees_status` tinyint(1) DEFAULT '1',
`employees_mobile` varchar(15) DEFAULT NULL,
`employees_designation` int(11) DEFAULT NULL,
`employees_bussiness_account` int(11) DEFAULT NULL,
`employees_image` varchar(255) DEFAULT NULL,
`employees_supervisers_id` int(11) DEFAULT NULL,
`employees_work_location_id` int(11) DEFAULT NULL,
`employees_date_added` datetime DEFAULT NULL,
PRIMARY KEY (`employees_id`),
UNIQUE KEY `employees_code_UNIQUE` (`employees_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;
--
-- Dumping data for table `employees`
--
INSERT INTO `employees` (`employees_id`, `employees_firstname`, `employees_middlename`, `employees_lastname`, `employee_gender`, `employees_dob`, `employees_emailaddress`, `employees_password`, `employees_datejoined`, `employees_code`, `employees_status`, `employees_mobile`, `employees_designation`, `employees_bussiness_account`, `employees_image`, `employees_supervisers_id`, `employees_work_location_id`, `employees_date_added`) VALUES
(16, 'Aneesh', 'C', 'S', 'M', '2012-11-05', 'aneesh.cs#calpinetech.com', '7106499a88fd79197ddbff61829993c9', '2010-12-07', 'cas927', 1, '9876543210', 1, 1, 'Betson.JPG', 0, 1, '2012-11-27 00:00:00'),
(17, 'Betson', 'T', 'Thomas', 'M', '2012-11-05', 'betson#calpinetech.com', '7106499a88fd79197ddbff61829993c9', '2008-12-06', 'cas450', 1, '9876543210', 6, 1, NULL, 16, 1, '2012-11-27 00:00:00'),
(18, 'test', 'test', 'test', 'M', '2012-11-12', 'test#calpinetech.com', '7106499a88fd79197ddbff61829993c9', '2012-11-06', 'cas999', 1, '9876543210', 1, 1, NULL, 16, 1, '2012-11-27 00:00:00'),
(19, 'asdsa', 'asdsad', 'asdsad', 'M', '2012-12-03', 'test#calpinetech.com', 'd8578edf8458ce06fbc5bb76a58c5ca4', '2012-12-24', 'ca0999', 1, '9876543210', 1, 1, NULL, 17, 1, '2012-12-04 00:00:00');
This is my table. Here employees_supervisers_id is the employees_id. How can we get the recursive data through cakephp?
I think that you are trying to create parent/child relationships between records in the same table. If that is what you are asking, you can create those relationships in the Employee model like this:
public $belongsTo = array(
'Supervisor' => array(
'className' => 'Employee',
'foreignKey' => 'employee_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
public $hasMany = array(
'Underlings' => array(
'className' => 'Employee',
'foreignKey' => 'employees_supervisers_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
);
CakePHP gets it by default if you create the relationships between models.
If you do:
$employees = $this->Employee->find('all');
And you have created the relationships between models, you would be able to access the recursive data with something like this:
$employees['Employee']['Supervisor']['employees_firstname'];
I would recommend you to take a look at the documentation referring to the linking between models:
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
To build a tree you need to use the TreeBehavior, and have parent_id and/or lft, rght field in your model.
lft and rght are for MPTT data
In your case you can configure the behavior to use your employees_supervisers_id field
Related
Table 'wp_users' already exists
Was working on a site offline and suddenly mysql port clash error came then I had to work on it solution for many hours but no luck. So I took the theme files and database manually from xampp and pasted them into a different computer system with a fresh xampp installed on it. This error is coming now which I have shared above. WordPress database error: [Table 'wp_users' already exists] CREATE TABLE wp_users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(255) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(255) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename), KEY user_email (user_email) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_usermeta' already exists] CREATE TABLE wp_usermeta ( umeta_id bigint(20) unsigned NOT NULL auto_increment, user_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (umeta_id), KEY user_id (user_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_termmeta' already exists] CREATE TABLE wp_termmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY term_id (term_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_terms' already exists] CREATE TABLE wp_terms ( term_id bigint(20) unsigned NOT NULL auto_increment, name varchar(200) NOT NULL default '', slug varchar(200) NOT NULL default '', term_group bigint(10) NOT NULL default 0, PRIMARY KEY (term_id), KEY slug (slug(191)), KEY name (name(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_term_taxonomy' already exists] CREATE TABLE wp_term_taxonomy ( term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default 0, taxonomy varchar(32) NOT NULL default '', description longtext NOT NULL, parent bigint(20) unsigned NOT NULL default 0, count bigint(20) NOT NULL default 0, PRIMARY KEY (term_taxonomy_id), UNIQUE KEY term_id_taxonomy (term_id,taxonomy), KEY taxonomy (taxonomy) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_term_relationships' already exists] CREATE TABLE wp_term_relationships ( object_id bigint(20) unsigned NOT NULL default 0, term_taxonomy_id bigint(20) unsigned NOT NULL default 0, term_order int(11) NOT NULL default 0, PRIMARY KEY (object_id,term_taxonomy_id), KEY term_taxonomy_id (term_taxonomy_id) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_commentmeta' already exists] CREATE TABLE wp_commentmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, comment_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY comment_id (comment_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_comments' already exists] CREATE TABLE wp_comments ( comment_ID bigint(20) unsigned NOT NULL auto_increment, comment_post_ID bigint(20) unsigned NOT NULL default '0', comment_author tinytext NOT NULL, comment_author_email varchar(100) NOT NULL default '', comment_author_url varchar(200) NOT NULL default '', comment_author_IP varchar(100) NOT NULL default '', comment_date datetime NOT NULL default '0000-00-00 00:00:00', comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', comment_content text NOT NULL, comment_karma int(11) NOT NULL default '0', comment_approved varchar(20) NOT NULL default '1', comment_agent varchar(255) NOT NULL default '', comment_type varchar(20) NOT NULL default '', comment_parent bigint(20) unsigned NOT NULL default '0', user_id bigint(20) unsigned NOT NULL default '0', PRIMARY KEY (comment_ID), KEY comment_post_ID (comment_post_ID), KEY comment_approved_date_gmt (comment_approved,comment_date_gmt), KEY comment_date_gmt (comment_date_gmt), KEY comment_parent (comment_parent), KEY comment_author_email (comment_author_email(10)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_links' already exists] CREATE TABLE wp_links ( link_id bigint(20) unsigned NOT NULL auto_increment, link_url varchar(255) NOT NULL default '', link_name varchar(255) NOT NULL default '', link_image varchar(255) NOT NULL default '', link_target varchar(25) NOT NULL default '', link_description varchar(255) NOT NULL default '', link_visible varchar(20) NOT NULL default 'Y', link_owner bigint(20) unsigned NOT NULL default '1', link_rating int(11) NOT NULL default '0', link_updated datetime NOT NULL default '0000-00-00 00:00:00', link_rel varchar(255) NOT NULL default '', link_notes mediumtext NOT NULL, link_rss varchar(255) NOT NULL default '', PRIMARY KEY (link_id), KEY link_visible (link_visible) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_options' already exists] CREATE TABLE wp_options ( option_id bigint(20) unsigned NOT NULL auto_increment, option_name varchar(191) NOT NULL default '', option_value longtext NOT NULL, autoload varchar(20) NOT NULL default 'yes', PRIMARY KEY (option_id), UNIQUE KEY option_name (option_name) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_postmeta' already exists] CREATE TABLE wp_postmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, post_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY post_id (post_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'wp_posts' already exists] CREATE TABLE wp_posts ( ID bigint(20) unsigned NOT NULL auto_increment, post_author bigint(20) unsigned NOT NULL default '0', post_date datetime NOT NULL default '0000-00-00 00:00:00', post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content longtext NOT NULL, post_title text NOT NULL, post_excerpt text NOT NULL, post_status varchar(20) NOT NULL default 'publish', comment_status varchar(20) NOT NULL default 'open', ping_status varchar(20) NOT NULL default 'open', post_password varchar(255) NOT NULL default '', post_name varchar(200) NOT NULL default '', to_ping text NOT NULL, pinged text NOT NULL, post_modified datetime NOT NULL default '0000-00-00 00:00:00', post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content_filtered longtext NOT NULL, post_parent bigint(20) unsigned NOT NULL default '0', guid varchar(255) NOT NULL default '', menu_order int(11) NOT NULL default '0', post_type varchar(20) NOT NULL default 'post', post_mime_type varchar(100) NOT NULL default '', comment_count bigint(20) NOT NULL default '0', PRIMARY KEY (ID), KEY post_name (post_name(191)), KEY type_status_date (post_type,post_status,post_date,ID), KEY post_parent (post_parent), KEY post_author (post_author) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT option_name FROM wp_options WHERE option_name in ( 'siteurl', 'home', 'blogname', 'blogdescription', 'users_can_register', 'admin_email', 'start_of_week', 'use_balanceTags', 'use_smilies', 'require_name_email', 'comments_notify', 'posts_per_rss', 'rss_use_excerpt', 'mailserver_url', 'mailserver_login', 'mailserver_pass', 'mailserver_port', 'default_category', 'default_comment_status', 'default_ping_status', 'default_pingback_flag', 'posts_per_page', 'date_format', 'time_format', 'links_updated_date_format', 'comment_moderation', 'moderation_notify', 'permalink_structure', 'rewrite_rules', 'hack_file', 'blog_charset', 'moderation_keys', 'active_plugins', 'category_base', 'ping_sites', 'comment_max_links', 'gmt_offset', 'default_email_category', 'recently_edited', 'template', 'stylesheet', 'comment_whitelist', 'blacklist_keys', 'comment_registration', 'html_type', 'use_trackback', 'default_role', 'db_version', 'uploads_use_yearmonth_folders', 'upload_path', 'blog_public', 'default_link_category', 'show_on_front', 'tag_base', 'show_avatars', 'avatar_rating', 'upload_url_path', 'thumbnail_size_w', 'thumbnail_size_h', 'thumbnail_crop', 'medium_size_w', 'medium_size_h', 'avatar_default', 'large_size_w', 'large_size_h', 'image_default_link_type', 'image_default_size', 'image_default_align', 'close_comments_for_old_posts', 'close_comments_days_old', 'thread_comments', 'thread_comments_depth', 'page_comments', 'comments_per_page', 'default_comments_page', 'comment_order', 'sticky_posts', 'widget_categories', 'widget_text', 'widget_rss', 'uninstall_plugins', 'timezone_string', 'page_for_posts', 'page_on_front', 'default_post_format', 'link_manager_enabled', 'finished_splitting_shared_terms', 'site_icon', 'medium_large_size_w', 'medium_large_size_h', 'wp_page_for_privacy_policy', 'show_comments_cookies_opt_in', 'initial_db_version' ) WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] INSERT INTO wp_options (option_name, option_value, autoload) VALUES ('siteurl', 'http://localhost/wordpress', 'yes'), ('home', 'http://localhost/wordpress', 'yes'), ('blogname', 'My Site', 'yes'), ('blogdescription', 'Just another WordPress site', 'yes'), ('users_can_register', '0', 'yes'), ('admin_email', 'you#example.com', 'yes'), ('start_of_week', '1', 'yes'), ('use_balanceTags', '0', 'yes'), ('use_smilies', '1', 'yes'), ('require_name_email', '1', 'yes'), ('comments_notify', '1', 'yes'), ('posts_per_rss', '10', 'yes'), ('rss_use_excerpt', '0', 'yes'), ('mailserver_url', 'mail.example.com', 'yes'), ('mailserver_login', 'login#example.com', 'yes'), ('mailserver_pass', 'password', 'yes'), ('mailserver_port', '110', 'yes'), ('default_category', '1', 'yes'), ('default_comment_status', 'open', 'yes'), ('default_ping_status', 'open', 'yes'), ('default_pingback_flag', '1', 'yes'), ('posts_per_page', '10', 'yes'), ('date_format', 'F j, Y', 'yes'), ('time_format', 'g:i a', 'yes'), ('links_updated_date_format', 'F j, Y g:i a', 'yes'), ('comment_moderation', '0', 'yes'), ('moderation_notify', '1', 'yes'), ('permalink_structure', '', 'yes'), ('rewrite_rules', '', 'yes'), ('hack_file', '0', 'yes'), ('blog_charset', 'UTF-8', 'yes'), ('moderation_keys', '', 'no'), ('active_plugins', 'a:0:{}', 'yes'), ('category_base', '', 'yes'), ('ping_sites', 'http://rpc.pingomatic.com/', 'yes'), ('comment_max_links', '2', 'yes'), ('gmt_offset', '0', 'yes'), ('default_email_category', '1', 'yes'), ('recently_edited', '', 'no'), ('template', 'twentynineteen', 'yes'), ('stylesheet', 'twentynineteen', 'yes'), ('comment_whitelist', '1', 'yes'), ('blacklist_keys', '', 'no'), ('comment_registration', '0', 'yes'), ('html_type', 'text/html', 'yes'), ('use_trackback', '0', 'yes'), ('default_role', 'subscriber', 'yes'), ('db_version', '44719', 'yes'), ('uploads_use_yearmonth_folders', '1', 'yes'), ('upload_path', '', 'yes'), ('blog_public', '1', 'yes'), ('default_link_category', '2', 'yes'), ('show_on_front', 'posts', 'yes'), ('tag_base', '', 'yes'), ('show_avatars', '1', 'yes'), ('avatar_rating', 'G', 'yes'), ('upload_url_path', '', 'yes'), ('thumbnail_size_w', '150', 'yes'), ('thumbnail_size_h', '150', 'yes'), ('thumbnail_crop', '1', 'yes'), ('medium_size_w', '300', 'yes'), ('medium_size_h', '300', 'yes'), ('avatar_default', 'mystery', 'yes'), ('large_size_w', '1024', 'yes'), ('large_size_h', '1024', 'yes'), ('image_default_link_type', 'none', 'yes'), ('image_default_size', '', 'yes'), ('image_default_align', '', 'yes'), ('close_comments_for_old_posts', '0', 'yes'), ('close_comments_days_old', '14', 'yes'), ('thread_comments', '1', 'yes'), ('thread_comments_depth', '5', 'yes'), ('page_comments', '0', 'yes'), ('comments_per_page', '50', 'yes'), ('default_comments_page', 'newest', 'yes'), ('comment_order', 'asc', 'yes'), ('sticky_posts', 'a:0:{}', 'yes'), ('widget_categories', 'a:0:{}', 'yes'), ('widget_text', 'a:0:{}', 'yes'), ('widget_rss', 'a:0:{}', 'yes'), ('uninstall_plugins', 'a:0:{}', 'no'), ('timezone_string', '', 'yes'), ('page_for_posts', '0', 'yes'), ('page_on_front', '0', 'yes'), ('default_post_format', '0', 'yes'), ('link_manager_enabled', '0', 'yes'), ('finished_splitting_shared_terms', '1', 'yes'), ('site_icon', '0', 'yes'), ('medium_large_size_w', '768', 'yes'), ('medium_large_size_h', '0', 'yes'), ('wp_page_for_privacy_policy', '0', 'yes'), ('show_comments_cookies_opt_in', '1', 'yes'), ('initial_db_version', '44719', 'yes') WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT option_value FROM wp_options WHERE option_name = 'home' WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT option_value FROM wp_options WHERE option_name = 'siteurl' WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SHOW FULL COLUMNS FROM `wp_options` WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('home', 'O:8:\"WP_Error\":2:{s:6:\"errors\";a:1:{s:30:\"wpdb_get_table_charset_failure\";a:1:{i:0;s:0:\"\";}}s:10:\"error_data\";a:0:{}}', 'yes') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`) WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT autoload FROM wp_options WHERE option_name = 'blodotgsping_url' WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT autoload FROM wp_options WHERE option_name = 'bodyterminator' WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT autoload FROM wp_options WHERE option_name = 'emailtestonly' WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT autoload FROM wp_options WHERE option_name = 'phoneemail_separator' WordPress database error: [Table 'iobm-emec.wp_options' doesn't exist in engine] SELECT autoload FROM wp_options WHERE option_name = 'smilies_directory' ... more code
That means your tables already exist. Try dropping them before running your SQL queries. Or use CREATE TABLE IF NOT EXISTS instead of just CREATE TABLE in your queries.
when you download wordpress it suggests to use wp_ as a prefix for your tables. but you cant have 2 tables with the same name online. what you have to do is during the wp installation is to change the prefix to something other than wp_. i had this problem myself when i made some projects in wp and had to upload them online and since the tables have the same names you cant have them in the same database/folder. simply just make sure to always give your project a unique prefix to avoid problems like this.
Issue with setDataSource in CakePHP 2.4.8
I wrote a behavior, Cascadable, that merges records across 2 databases. It works sort of like CSS, where the more local style overrides the global. The behavior uses $this->setDataSource() to switch between the databases. This was working up until the 2.4.8 release when this commit was made to the Model.php file. Here's sort of an extraction from the behavior: $Model->setDataSource( 'alt' ); $altData = $Model->find($findType, array( 'contain' => false, 'conditions' => array( $Model->alias.'.id' => $ids ), 'callbacks' => 'before' )); If the callbacks option is set to false, I get Missing Database Table errors about tables that are only present in the default (parent) datasource. I'm not sure what I'm doing wrong here, but after 2.4.8 upgrade it always uses the wrong (parent) database instead of the child. I can revert Model.php back to the 2.4.7 version to fix the issue. I realize this is difficult to replicate because it only breaks in my very specific database structure. MySQL Table Schema example: Parent Database Table CREATE TABLE `products` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL DEFAULT '', `price` float(8,2) DEFAULT NULL, `active` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`), KEY `active` (`active`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0; INSERT INTO `parent_db`.`products` (`id`, `name`, `price`, `active`) VALUES (NULL, 'Big Box of Goodies', '99.99', '0'); Child Database Table CREATE TABLE `products` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `price` float(8,2) DEFAULT NULL, `active` tinyint(1) DEFAULT NULL, PRIMARY KEY (`id`), KEY `active` (`active`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0; INSERT INTO `child_db`.`products` (`id`, `name`, `price`, `active`) VALUES (NULL, 'Small Box of Surprises', NULL, '1'); Query Results From Parent DB array( (int) 0 => array( 'Product' => array( 'id' => '1149', 'name' => 'Big Box of Goodies', 'price' => '99.99', 'active' => false ) ) ) From Child DB with working Cascadable behavior (child record is merged into parent record, ignoring null values) array( (int) 0 => array( 'Product' => array( 'id' => '1149', 'name' => 'Small Box of Surprises', 'price' => '99.99', 'active' => true ) ) ) Workaround: Setting the schemaName manually after using setDataSource fixes the issue for me. $Model->setDataSource( 'alt' ); App::uses('ConnectionManager', 'Model'); $dataSources = ConnectionManager::enumConnectionObjects(); $Model->schemaName = $dataSources['alt']['database'];
Column not found, retrieving data associated model
I've got the following find() function $this->User->find('all',array( 'conditions' => array('User.id' => $this->Auth->user('id')), 'fields' => array('User.id','UserRole.id') )); And the following associations are defined // UserRole.php class UserRole extends AppModel { public $belongsTo = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id' ) ); } // User.php class User extends AppModel { public $hasMany = array( 'UserRole' => array( 'className' => 'UserRole', 'foreignKey' => 'user_id', 'dependent' => false, ) ); } And In App model recursive is set to -1 public $recursive = -1; The database tables are the following: CREATE TABLE IF NOT EXISTS `user_roles` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `event_id` int(10) unsigned NOT NULL, `role_id` int(10) unsigned NOT NULL, `user_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) But I get the vollowing error Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UserRole.id' in 'field list' SQL Query: SELECT `User`.`id`, `UserRole`.`id` FROM `atlanta`.`users` AS `User` WHERE `User`.`id` = 5 I get that cake can't find the UserRole.id, but what did I do wrong?
Either you use some behavior like Containable and your find() will look like this $this->User->find('all',array( 'conditions' => array('User.id' => $this->Auth->user('id')), 'contain' => array( 'UserRole' => array( 'fields'=>array('id') ) ), 'fields' => array('id') )); OR you set recursive to 1 $this->User->find('all',array( 'conditions' => array('User.id' => $this->Auth->user('id')), 'fields' => array('User.id'), // UPDATE: unfortunately you cant specify associated models fields without behavior 'recursive' => 1 )); The thing is that when recursive is set to -1 or 0 it does not fetch associated models unless some behavior takes care of that for e.g. Containable or Linkable.
Polymorphic associations in CakePHP2
I have 3 models, Page , Course and Content Page and Course contain meta data and Content contains HTML content. Page and Course both hasMany Content Content belongsTo Page and Course To avoid having page_id and course_id fields in Content (because I want this to scale to more than just 2 models) I am looking at using Polymorphic Associations. I started by using the Polymorphic Behavior in the Bakery but it is generating waaay too many SQL queries for my liking and it's also throwing an "Illegal Offset" error which I don't know how to fix (it was written in 2008 and nobody seems to have referred to it recently so perhaps the error is due to it not having been designed for Cake 2?) Anyway, I've found that I can almost do everything I need by hardcoding the associations in the models as such: Page Model CREATE TABLE `pages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `updated` datetime NOT NULL, PRIMARY KEY (`id`) ) <?php class Page extends AppModel { var $name = 'Page'; var $hasMany = array( 'Content' => array( 'className' => 'Content', 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Page'), ) ); } ?> Course Model CREATE TABLE `courses` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `updated` datetime NOT NULL, PRIMARY KEY (`id`) ) <?php class Course extends AppModel { var $name = 'Course'; var $hasMany = array( 'Content' => array( 'className' => 'Content', 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Course'), ) ); } ?> Content model CREATE TABLE IF NOT EXISTS `contents` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `class` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `foreign_id` int(11) unsigned NOT NULL, `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `content` text COLLATE utf8_unicode_ci NOT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) <?php class Content extends AppModel { var $name = 'Content'; var $belongsTo = array( 'Page' => array( 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Page') ), 'Course' => array( 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Course') ) ); } ?> The good thing is that $this->Content->find('first') only generates a single SQL query instead of 3 (as was the case with the Polymorphic Behavior) but the problem is that the dataset returned includes both of the belongsTo models, whereas it should only really return the one that exists. Here's how the returned data looks: array( 'Content' => array( 'id' => '1', 'class' => 'Course', 'foreign_id' => '1', 'title' => 'something about this course', 'content' => 'The content here', 'created' => null, 'modified' => null ), 'Page' => array( 'id' => null, 'title' => null, 'slug' => null, 'created' => null, 'updated' => null ), 'Course' => array( 'id' => '1', 'title' => 'Course name', 'slug' => 'name-of-the-course', 'created' => '2012-10-11 00:00:00', 'updated' => '2012-10-11 00:00:00' ) ) I only want it to return one of either Page or Course depending on which one is specified in Content.class UPDATE: Combining the Page and Course models would seem like the obvious solution to this problem but the schemas I have shown above are just shown for the purpose of this question. The actual schemas are actually very different in terms of their fields and the each have a different number of associations with other models too. UPDATE 2 Here is the query that results from running $this->Content->find('first'); : SELECT `Content`.`id`, `Content`.`class`, `Content`.`foreign_id`, `Content`.`title`, `Content`.`slug`, `Content`.`content`, `Content`.`created`, `Content`.`modified`, `Page`.`id`, `Page`.`title`, `Page`.`slug`, `Page`.`created`, `Page`.`updated`, `Course`.`id`, `Course`.`title`, `Course`.`slug`, `Course`.`created`, `Course`.`updated` FROM `cakedb`.`contents` AS `Content` LEFT JOIN `cakedb`.`pages` AS `Page` ON (`Content`.`foreign_id` = `Page`.`id` AND `Content`.`class` = 'Page') LEFT JOIN `cakedb`.`courses` AS `Course` ON (`Content`.`foreign_id` = `Course`.`id` AND `Content`.`class` = 'Course') WHERE 1 = 1 LIMIT 1
Your query is okay. Just filter empty values after find: public function afterFind($results, $primary = false) { return Set::filter($results, true); } Take a look at this question. You can also try to provide conditions to you find query that Page.id in not null or Course.id is not null.
Denoting multi-dimensional array data in relational database table?
Say I have an object-like data record like this: $article = array( 'title' => '', 'tagline' => '', 'content' => '', 'stats' => array( 'words' => 0, 'paragraphs' => 0, 'tables' => 0 ), 'references' => array( 'reference 1', 'reference 2', 'reference 3' ), 'attachments' => array( 'images' => array( 'image 1', 'image s' ), 'videos' => array( 'video 1', 'video 2' ) ) ); My question is how can I store this array of data record in relational database? How should I design the table structure? I know I can always set up flat fields such as stats_words, stats_paragraphs, and so forth but is there any more structural ways? Instead of storing a JSON or serialized string in a single field.... Thanks!
For example this way: article ID title _ tagline _ content ___ stat_words stat_paragraphs stat_tables article_reference ID article_id -> article reference _ article_attachment ID article_id -> article att_type // image or video path _ title _ (_ means varchar/text fields, other fields are numbers) Or as MySQL DDL: CREATE TABLE IF NOT EXISTS article ( id INT NOT NULL AUTO_INCREMENT, title VARCHAR(255) NOT NULL, tagline VARCHAR(255) NOT NULL, content MEDIUMTEXT NOT NULL, stat_words INT NOT NULL, stat_paragraphs INT NOT NULL, stat_tables INT NOT NULL, PRIMARY KEY ( id ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; CREATE TABLE IF NOT EXISTS article_reference ( id INT NOT NULL AUTO_INCREMENT, article_id INT NOT NULL, reference VARCHAR(255) NOT NULL, PRIMARY KEY ( id ), FOREIGN KEY ( article_id ) REFERENCES article( id ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; CREATE TABLE IF NOT EXISTS article_attachment ( id INT NOT NULL AUTO_INCREMENT, article_id INT NOT NULL, att_type INT NOT NULL, path VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, PRIMARY KEY ( id ), FOREIGN KEY ( article_id ) REFERENCES article( id ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;