Implementing relationships in CakePHP Model - mysql

I am new to Cake and am trying to implement the Model layer as best as I can by using the bake script.
The implementation of my DB relationships has me a little worried though.
CREATE TABLE IF NOT EXISTS `model_base_test`.`entrys` (
`id` INT NOT NULL AUTO_INCREMENT,
`entry_year` INT(2) NOT NULL,
`contact_id` INT NOT NULL,
`division_id` INT NOT NULL,
`category_id` INT NOT NULL,
`entry_name` VARCHAR(45) NULL DEFAULT NULL,
`scale` VARCHAR(10) NULL DEFAULT NULL,
`ootb` TINYINT(1) NULL DEFAULT NULL,
`scratch` TINYINT(1) NULL DEFAULT NULL,
`theme` TINYINT(1) NULL DEFAULT NULL,
`score` DECIMAL(4,2) NULL DEFAULT NULL,
`medal_id` INT NULL DEFAULT NULL,
`image_id` INT NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `fk_entries_contacts_idx` (`contact_id` ASC),
INDEX `fk_entries_groups_idx` (`category_id` ASC),
INDEX `fk_entries_medals_idx` (`medal_id` ASC),
UNIQUE INDEX `entry_id_UNIQUE` (`id` ASC),
INDEX `fk_entrys_divisions_idx` (`division_id` ASC),
CONSTRAINT `fk_entries_contacts`
FOREIGN KEY (`contact_id`)
REFERENCES `model_base_test`.`contacts` (`id`)
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `fk_entries_groups`
FOREIGN KEY (`category_id`)
REFERENCES `model_base_test`.`categorys` (`id`)
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `fk_entries_medals`
FOREIGN KEY (`medal_id`)
REFERENCES `model_base_test`.`medals` (`id`)
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `fk_entrys_divisions`
FOREIGN KEY (`division_id`)
REFERENCES `model_base_test`.`divisions` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `model_base_test`.`scores` (
`id` INT NOT NULL AUTO_INCREMENT,
`judge_id` INT NOT NULL,
`entry_id` INT NOT NULL,
`criteria` VARCHAR(15) NULL DEFAULT NULL,
`possible_points` INT NULL DEFAULT NULL,
`entry_possible` TINYINT(1) NULL DEFAULT NULL,
`raw_score` INT NULL DEFAULT NULL,
`score_adjustment` INT NULL DEFAULT NULL,
`weighted_score` DECIMAL(5,2) NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `fk_scores_entries_idx` (`entry_id` ASC),
UNIQUE INDEX `id_UNIQUE` (`id` ASC),
CONSTRAINT `fk_scores_entries1`
FOREIGN KEY (`entry_id`)
REFERENCES `model_base_test`.`entrys` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
With the above tables and constraints as example, how best can I implement with Cake? The above is an optional one-to-many relationship, i.e. there is not necessarily a Score row for the mandatory Entry row.

Related

Alter table foreign key constraint fails

When I try to do this:
ALTER TABLE credit_card ADD CONSTRAINT fk_company FOREIGN KEY (company_id) REFERENCES company (id);
I got the error a foreign key constraint fails, but I don't understand why. The company_id column has same type of company.id column as you can see:
Company table
CREATE TABLE `company` (
`id` bigint NOT NULL AUTO_INCREMENT,
`code` varchar(10) NOT NULL,
`description` varchar(50) NOT NULL,
`currency_id` bigint NOT NULL,
`language_id` bigint DEFAULT NULL,
`address_id` bigint DEFAULT NULL,
`creation_time` datetime NOT NULL,
`modification_time` datetime DEFAULT NULL,
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`cost_center_modifiable` tinyint(1) DEFAULT NULL,
`use_colleague_cost_center` tinyint(1) DEFAULT NULL,
`fixed_guest_company` varchar(50) DEFAULT NULL,
`info_number` int DEFAULT NULL,
`use_kilometric_rate` tinyint(1) DEFAULT NULL,
`use_multiple_km_rate` tinyint(1) DEFAULT NULL,
`email_required` tinyint(1) DEFAULT NULL,
`logo` varchar(255) DEFAULT NULL,
`holding_id` bigint NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`),
KEY `fk_company_address1` (`address_id`),
KEY `fk_company_currency1` (`currency_id`),
KEY `company_language_FK` (`language_id`),
KEY `company_holding_FK` (`holding_id`),
CONSTRAINT `company_currency_FK` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`),
CONSTRAINT `company_holding_FK` FOREIGN KEY (`holding_id`) REFERENCES `holding` (`id`),
CONSTRAINT `company_language_FK` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Credit_card table
CREATE TABLE `credit_card` (
`id` bigint NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`pan` varchar(16) NOT NULL,
`account` varchar(50) DEFAULT NULL,
`begin_date` date NOT NULL,
`end_date` date NOT NULL,
`disabled` tinyint(1) NOT NULL DEFAULT '0',
`creation_time` datetime NOT NULL,
`modification_time` datetime DEFAULT NULL,
`company_id` bigint NOT NULL,
PRIMARY KEY (`id`),
KEY `username` (`username`),
KEY `pan` (`pan`),
CONSTRAINT `fk_credit_card_user_ext` FOREIGN KEY (`username`) REFERENCES `users_extension` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8mb3
Dont make auto increment columns as foreign keys or unless not sure, dont reference these to autoincrement columns as it may end up making the table with foreign key issue a constraint violation if redundant entries are expected to be made in either of the tables.
Might be the case the related data is already ingested and then the table is altered

SQL Foreign Key

I'm reading a book about e-commerce. In this book I found the folowing SQL code:
CREATE TABLE `orders` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`users_id` INT UNSIGNED NOT NULL,
`transaction_id` VARCHAR(45) NOT NULL,
`payment_status` VARCHAR(45) NOT NULL,
`payment_amount` INT UNSIGNED NOT NULL,
`date_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `date_created` (`date_created` ASC),
INDEX `transaction_id` (`transaction_id` ASC),
CONSTRAINT `fk_orders_users1`
FOREIGN KEY (`id`)
REFERENCES `users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE = InnoDB DEFAULT CHARSET=utf8;
The book says that the CONSTRAINT would prevent the insertion of a "users_id" that doesn't match a 'id' in the table 'users'. By reading the code, I believe the book is wrong, because I believe this code would acctualy prevent the insertion of a "id" (in the table "orders") that doesn't match the field "id" (in the table users). I am right?
Sorry for bad english. I'm not american and trying my best...
Corrected code:
CREATE TABLE `orders` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`users_id` INT UNSIGNED NOT NULL,
`transaction_id` VARCHAR(45) NOT NULL,
`payment_status` VARCHAR(45) NOT NULL,
`payment_amount` INT UNSIGNED NOT NULL,
`date_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `date_created` (`date_created` ASC),
INDEX `transaction_id` (`transaction_id` ASC),
CONSTRAINT `fk_orders_users1`
FOREIGN KEY (`users_id`)
REFERENCES `users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE = InnoDB DEFAULT CHARSET=utf8;

In My Project i have x_user_module_perm table for which i need to keep one primary key and one composite primary key

i am using a syntax :-
CREATE TABLE `x_user_module_perm` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NULL DEFAULT NULL,
`module_id` bigint(20) NULL DEFAULT NULL,
`create_time` datetime NULL DEFAULT NULL,
`update_time` datetime NULL DEFAULT NULL,
`added_by_id` bigint(20) NULL DEFAULT NULL,
`upd_by_id` bigint(20) NULL DEFAULT NULL,
`is_allowed` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
PRIMARY KEY (`user_id`,`module_id`),
KEY `x_user_module_perm_idx_module_id` (`module_id`),
KEY `x_user_module_perm_idx_user_id` (`user_id`),
CONSTRAINT `x_user_module_perm_FK_module_id` FOREIGN KEY (`module_id`) REFERENCES `x_modules_master` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `x_user_module_perm_FK_user_id` FOREIGN KEY (`user_id`) REFERENCES `x_portal_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ;
I am getting a error cannot use two primary key's
Do is it possible, Guy's please Guide me !!!
Try changing PRIMARY KEY (user_id,module_id) to UNIQUE INDEX(user_id,module_id)

having trouble with my database using workbench

I am creating a test database to train with and am running into this problem -
"Schema Creation Failed: Can't create table 'db_2_5b129.tbluserassignment' (errno: 150): "
The code for the specific table is -
-- Table tblUserAssignment
CREATE TABLE IF NOT EXISTS `tblUserAssignment` (
`assignment_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`supervisor_id` INT NOT NULL,
`position_id` INT NOT NULL,
`department_id` INT NOT NULL,
`start_date` DATE NOT NULL,
`end_date` DATE NOT NULL,
`date_added` DATE NOT NULL,
`date_modified` DATETIME NOT NULL,
`date_deleted` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`assignment_id`),
INDEX `fk_tblUserAssignment_tblUserPhone1_idx` (`user_id` ASC),
INDEX `fk_tblUserAssignment_tblUserPositions1_idx` (`position_id` ASC),
CONSTRAINT `fk_tblUserAssignment_tblUserPhone1`
FOREIGN KEY (`user_id`)
REFERENCES `tblUserPhone` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tblUserAssignment_tblUserPositions1`
FOREIGN KEY (`position_id`)
REFERENCES `tblUserPositions` (`position_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Can someone look it over and point me in the right direction?
problem is in differences between forign fields type
tblUserPositions.position_id INT UNSIGNED NOT NULL AUTO_INCREMEN
and
tblUserAssignment.position_id INT NOT NULL,`
EDIT 1
see this Use Composite Primary Key as Foreign Key
EDIT 2
this one tested & works fine
CREATE TABLE `tbluserphone` (
`contact_information_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(11) NOT NULL,
`phone_number` VARCHAR(20) NOT NULL,
`phone_type_id` INT(11) NOT NULL,
`date_added` DATETIME NOT NULL,
`date_modified` DATETIME NOT NULL,
`date_deleted` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`contact_information_id`, `user_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
CREATE TABLE `tbluserassignment` (
`assignment_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`contact_information_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(11) NOT NULL,
`supervisor_id` INT(11) NOT NULL,
`position_id` INT(10) UNSIGNED NOT NULL,
`department_id` INT(11) NOT NULL,
`start_date` DATE NOT NULL,
`end_date` DATE NOT NULL,
`date_added` DATE NOT NULL,
`date_modified` DATETIME NOT NULL,
`date_deleted` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`assignment_id`),
INDEX `fk_tblUserAssignment_tblUserPhone1_idx` (`user_id`),
INDEX `fk_tblUserAssignment_tblUserPositions1_idx` (`position_id`),
INDEX `contact` (`contact_information_id`),
CONSTRAINT `FK_tbluserassignment_tbluserpositions`
FOREIGN KEY (`position_id`)
REFERENCES `tbluserpositions` (`position_id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT tbluserassignment_fkz1
FOREIGN KEY (contact_information_id, user_id)
REFERENCES tbluserphone (contact_information_id, user_id)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
(contact_information_id, user_id) - fields should goes same way, like in primary key difinition

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row on CONSTRAINT `fk_users_has_ratings_businesses1

I'm getting this error when i try to insert new ratings
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yuldi`.`users_ratings`, CONSTRAINT `fk_users_has_ratings_businesses1` FOREIGN KEY (`business_id`) REFERENCES `businesses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
below database table structure with some foreign keys. i'm confused with adding multiple primary and foreign keys. please help me to sort out this issue
CREATE TABLE IF NOT EXISTS `yuldi`.`businesses` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`state` VARCHAR(100) NOT NULL,
`slug` VARCHAR(250) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`suburb` VARCHAR(100) NOT NULL,
`business_name` VARCHAR(100) NOT NULL,
`business_address` VARCHAR(250) NOT NULL,
`business_postal` VARCHAR(10) NOT NULL,
`business_postal_id` INT(11) NOT NULL,
`business_phone` VARCHAR(50) NOT NULL,
`business_phone1` VARCHAR(50) NOT NULL,
`business_phone2` VARCHAR(50) NOT NULL,
`business_email` VARCHAR(100) NOT NULL,
`business_website` VARCHAR(200) NOT NULL,
`business_details` VARCHAR(5000) NOT NULL,
`business_openinghours` VARCHAR(200) NOT NULL,
`business_service` VARCHAR(200) NOT NULL,
`business_addtionalinfo` VARCHAR(200) NOT NULL,
`business_lat` FLOAT(10,6) NOT NULL,
`business_lng` FLOAT(10,6) NOT NULL,
`identity` VARCHAR(100) NOT NULL,
`status` INT(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 232
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`ratings` (
`id` VARCHAR(36) NOT NULL,
`model` VARCHAR(255) NOT NULL,
`value` FLOAT(8,4) NULL DEFAULT '0.0000',
`comment` TEXT NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQUE_RATING` (`model` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_email` VARCHAR(255) NULL DEFAULT NULL,
`user_password` CHAR(100) NULL DEFAULT NULL,
`user_name` VARCHAR(255) NULL DEFAULT NULL,
`user_code` VARCHAR(255) NULL DEFAULT NULL,
`user_status` TINYINT(4) NULL DEFAULT '0',
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`ip_address` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 14
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users_ratings` (
`user_id` INT(11) NOT NULL,
`rating_id` VARCHAR(36) NOT NULL,
`business_id` INT(11) NOT NULL,
PRIMARY KEY (`user_id`, `rating_id`, `business_id`),
INDEX `fk_users_has_ratings_ratings1_idx` (`rating_id` ASC),
INDEX `fk_users_has_ratings_users1_idx` (`user_id` ASC),
INDEX `fk_users_has_ratings_businesses1_idx` (`business_id` ASC),
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_ratings1`
FOREIGN KEY (`rating_id`)
REFERENCES `yuldi`.`ratings` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_users1`
FOREIGN KEY (`user_id`)
REFERENCES `yuldi`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
The problem is coming from this:
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
The record you're trying to insert / update - probably user_ratings - is foreign keyed to the businesses table; you can't create a user_ratings record without a business_id, and that business_id must actually exist as an id in the businesses table.