I have a problem while trying to save data (or update) in a crud with n_n relation, i have a product table, who is related to a product_detail, product detail has 3 foreign keys, to connect to a table called color, and other called material. Any idea why fail?, i appreciate your help, thanks.
The error is this:
A Database Error Occurred
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (medina_db.product_detail, CONSTRAINT product_detail_ibfk_3 FOREIGN KEY (material_id) REFERENCES material (id))
INSERT INTO product_detail (product_id, color_id) VALUES ('4', '1')
Filename: /Applications/MAMP/htdocs/industrias_medina/models/grocery_crud_model.php
Line Number: 413
My Grocery Crud code:
$crud = new grocery_CRUD();
$crud->set_table('product')->set_subject('Productos');
$crud->set_relation_n_n("Colores", 'product_detail', 'color', 'product_id', 'color_id', 'name');
$crud->set_relation_n_n("Materiales", 'product_detail', 'material', 'product_id', 'material_id', 'name');
$crud->set_field_upload('image','assets/uploads/files');
$crud->fields('name','model','description', "Colores", "Materiales", 'image');
$output = $crud->render();
$this->_productos_output($output);
SQL:
CREATE TABLE `color` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=ucs2 AUTO_INCREMENT=2 ;
CREATE TABLE `material` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Unique identifier',
`name` varchar(250) NOT NULL COMMENT 'Product''s name',
`model` varchar(250) NOT NULL COMMENT 'Product''s model',
`description` varchar(400) NOT NULL COMMENT 'Product''s description',
`image` varchar(400) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Table to store products' AUTO_INCREMENT=13 ;
CREATE TABLE `product_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`color_id` int(11) NOT NULL,
`material_id` int(11) NOT NULL,
PRIMARY KEY (`id`,`product_id`,`color_id`,`material_id`),
KEY `product_id` (`product_id`),
KEY `color_id` (`color_id`),
KEY `material_id` (`material_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=14 ;
It looks like your product_detail table has a material_id column that references the material table. Your insert statement is not inserting anything into that material_id column. You need to either insert a value into that column (that exists in material), set a default value that references the key in material, or set a default of NULL for that column.
Thanks,
Andrew
Related
I am trying to create a campus structure. So buildings have floors, floors have rooms. I am trying to create a relational database such that multiple rooms relate to one floor and multiple floors relate to their building.
Here is my structure for the building and floor tables:
CREATE TABLE `building` (
`id` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
CREATE TABLE `floor` (
`id` int(11) NOT NULL,
`building_id` int(11) DEFAULT NULL,
`level` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `floor_building_id__fk` (`building_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
I want to insert more than one floor in the floor table relating to the same building_id using:
INSERT INTO `floor` SET id=3, `number` = 420, building_id=(SELECT id FROM building WHERE id=2);
However I keep getting the following error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`seatspace`.`floor`, CONSTRAINT `building_id` FOREIGN KEY (`id`) REFERENCES `building` (`id`))
I want to insert, update and delete floors relating to their specified building_id. Any help would be appreciated.
I have fixed the problem by changing the constraint name for the foreign key. I also rewrote parts of the schema so all of the desired columns were present. Here is the final schema and CRUD.
CREATE TABLE `floor` (
`floor_id` int(11) NOT NULL AUTO_INCREMENT,
`number` int(11) NOT NULL,
`building_id` int(11) NOT NULL,
PRIMARY KEY (`floor_id`),
UNIQUE KEY `floor_id_UNIQUE` (`floor_id`),
KEY `building_id_idx` (`building_id`),
CONSTRAINT `building_id` FOREIGN KEY (`building_id`) REFERENCES `building`
(`building_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
INSERT INTO `floor` (floor_id, `number`, building_id) VALUES (default, 3,
(SELECT building_id FROM building WHERE building_id=2)) ;
UPDATE `floor` SET `number`=3, building_id=1 WHERE floor_id=2;
DELETE FROM `floor` WHERE floor_id=3;
CREATE TABLE `building` (
`building_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`building_id`),
UNIQUE KEY `building_id_UNIQUE` (`building_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
INSERT INTO building (building_id, name) VALUES (DEFAULT, '1 West');
UPDATE `building` SET `name`='3 West' WHERE building_id=2;
DELETE FROM `building` WHERE building_id=2;
I am trying to create foreign key in one of my table but i am getting this error can you help with this
CREATE TABLE IF NOT EXISTS `albums` (
`id` smallint(5) unsigned NOT NULL,
`url` mediumtext NOT NULL,
`year` mediumint(9) NOT NULL,
`album_name` varchar(150) NOT NULL,
`album_cover` text NOT NULL,
`tracks_id` text NOT NULL,
`category` tinyint(4) NOT NULL,
`reciter` tinyint(4) NOT NULL,
`keywords` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Foreign Key Table Structure
CREATE TABLE IF NOT EXISTS `album_likes` (
`album_id` int(5) NOT NULL,
`likes` int(11) NOT NULL,
`dislikes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now what i did to make this foreign key is that i went to the structure of this table in phpmyadmin and then add constraint name select the columns
Here is the query
ALTER TABLE `album_likes` ADD CONSTRAINT `album_like_fk` FOREIGN KEY (`album_id`) REFERENCES `mp3script`.`albums`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
The output i got
1215 - Cannot add foreign key constraint
A foreign key requires an index on the column you are referencing, in this case albums.id.
Add the index:
CREATE INDEX ids_nn_1 on albums(id);
And you create foreign key should work
I found this useful Internationalization code:
http://pastebin.com/SyKmPYTX
everything works well except I am unable to connect to database.
what I need:
1) I need to check last segment
2) this is my db
DROP TABLE IF EXISTS `translate`;
DROP TABLE IF EXISTS `trans_data`;
DROP TABLE IF EXISTS `languages`;
/*Table structure for table `languages` */
CREATE TABLE `languages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`key` varchar(5) NOT NULL,
`default` tinyint(1) NOT NULL DEFAULT '0',
`display` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*Data for the table `languages` */
insert into `languages`(`name`,`key`,`default`,`display`) values
('GEO','ka',1,1),
('ENG','en',0,1),
('RUS','ru',0,1);
/*Table structure for table `trans_data` */
CREATE TABLE `trans_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*Table structure for table `translate` */
CREATE TABLE `translate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lang` int(11) NOT NULL,
`data` int(11) NOT NULL,
`trans` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `lang_2` (`lang`,`data`),
KEY `lang` (`lang`),
KEY `data` (`data`),
CONSTRAINT `translate_ibfk_1` FOREIGN KEY (`lang`) REFERENCES `languages` (`id`),
CONSTRAINT `translate_ibfk_2` FOREIGN KEY (`data`) REFERENCES `trans_data` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=340 DEFAULT CHARSET=utf8;
in the first I need to do something like this
$this->db->where('key', end($this->segments));
$query = $this->db->get('languages');
$lang = $query->row();
if(empty($lang)){
$this->db->where('default', 1);
$query2 = $this->db->get('languages');
$lang = $query2->row();
}
$lang_array = [
"lang_key" => $lang->key,
"lang_id" => $lang->id
];
$this->session->set_userdata($lang_array);
if(end($this->uri->segment_array()) == $lang->key){
unset($this->uri->segments[intval($this->uri->total_segments() - 1)]);
}
after this functionality
then I need to download translates from database and save it in object with this query
SELECT TD.`name` , T.`trans`
FROM `translate` AS T
INNER JOIN `languages` AS L ON (T.`lang` = L.`id`)
INNER JOIN `trans_data` AS TD ON (T.`data` = TD.`id`)
WHERE (L.`key` = :lang_key);
and when I call from view
echo $this->lang->line('trans_key');
I need to get the value
but I do not undestand how to edit this class to do this job...
can you help me and edit this class for me?
thank you for future...
HI i never faced this type of problem. Please clarify me when i did wrong. I tried to generate 2 model which have relation but it didn't come in models. Here are the Db structure.
CREATE TABLE IF NOT EXISTS `property` (
`property_id` int(11) NOT NULL AUTO_INCREMENT,
`ListPrice` int(11) NOT NULL,
`ListingURL` text NOT NULL,
`ProviderName` varchar(255) NOT NULL,
`ProviderURL` text NOT NULL,
`modificationTimestamp` text NOT NULL,
PRIMARY KEY (`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `location` (
`loc_id` int(11) NOT NULL AUTO_INCREMENT,
`property_id` int(11) NOT NULL,
`latitude` varchar(255) NOT NULL DEFAULT '0.0000',
`longitude` varchar(255) NOT NULL DEFAULT '0.0000',
PRIMARY KEY (`loc_id`),
KEY `property_id` (`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
--
-- Constraints for table `location`
--
ALTER TABLE `location`
ADD CONSTRAINT `location_ibfk_1` FOREIGN KEY (`property_id`)
REFERENCES `property` (`property_id`) ON DELETE CASCADE ON UPDATE CASCADE;
In model no relation in there :
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
This happens sometimes with the gii tool. What you need to do is to comment the relation in the table itself. gii misses the rleationship sometimes but mostly picks it up if available in the comment. So, modify your tables and comment the foreign key as below, it should work.
CREATE TABLE IF NOT EXISTS `location` (
`loc_id` int(11) NOT NULL AUTO_INCREMENT,
`property_id` int(11) NOT NULL COMMENT 'Foreign Key (property_id) references property(property_id )',
`latitude` varchar(255) NOT NULL DEFAULT '0.0000',
`longitude` varchar(255) NOT NULL DEFAULT '0.0000',
PRIMARY KEY (`loc_id`),
KEY `property_id` (`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
users table:
CREATE TABLE `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`unique_id` varchar(23) NOT NULL,
`full_name` varchar(100) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `unique_id` (`unique_id`) USING BTREE,
UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8;
items table:
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_photo` text,
`item_name` varchar(100) DEFAULT NULL,
`item_description` varchar(500) DEFAULT NULL,
`item_price` varchar(10) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_user_id` (`user_id`) USING BTREE,
KEY `fk_category_id` (`category_id`) USING BTREE,
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`),
CONSTRAINT `items_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8;
What I would wanna do is to create a private messaging system for my project. Before this I have implemented a Comment system and it works well (pull out comments which has the same item_id). You can see the DDL and query here. But when it come to this, I find it hard to think about private messaging model.
Basically, the private message is to bid the item price between TWO users only (the seller and the bidder). Other registered user cannot see others bidding.
Here's my try at creating Bids table:
CREATE TABLE `bids` (
`id` int(11) NOT NULL,
`bid` float DEFAULT NULL,
`message` varchar(255) DEFAULT NULL,
`from_uid` varchar(255) DEFAULT NULL,
`to_uid` varchar(255) DEFAULT NULL,
`to_iid` int(11) DEFAULT NULL,
`time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I have also tried to make Foreign Keys into bids table, but it seems like it's already too complicated for me. So an error 1215 - Cannot add foreign key constraint came out :(
If anything just let me know.
EDIT: charset to utf8. Failed to create Foreign key constraints
MESSAGES
message_id
conversation_id
user_id
message
CONVERSATIONS
conversation_id
item_id
user_id
BIDS
bid_id
item_id
user_id
amount