Yii model not bulid relation automatically using gii - php

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;

Related

Unable to create foreign key in PHPmyadmin

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

Yii2-Integrity constraint violation – yii\db\IntegrityException

Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
The SQL being executed was: INSERT INTO `employee` (`client_code`, `company_name`, `emp_email`, `emp_mobile`, `emp_first_name`, `emp_last_name`) VALUES ('12345678', 'PVPPCOE', 'saurabhkulkarni2010#hotmail.com', '+449029792183', 'Saurabh', 'Kulkarni')
Error Info: Array
(
[0] => 23000
[1] => 1452
[2] => Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
)
I have three tables Client, Employee and create_client, out of which client and employee has two foreign keys.
This problem is showing when I try to insert data from create_client to employee which has exact same field.
What should I do so that I can insert two tables at one i.e create_client and employee
UPDATE-
Table Structure
1)client
CREATE TABLE IF NOT EXISTS `client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
2)create_client
CREATE TABLE IF NOT EXISTS `create_client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;
3)employee
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
This is my table structure, first user will create client that means first it will update create_client. Now if user wants he can add many employee under one client code now user will update employee table from Yii2 dynamic form widget.
For using this widget I have created one table call client this will store only client_code and company name remaining data will go in employee table e.g emp_mobile,emp_email, emp_first_name, emp_last_name.
Now this problem is pop up when user first enters data into create_client table.
everything is working between client and employee table user able to enter as many employee as it wants using Yii2 dynamic form Widget but not working for create_client
Apparently you also have a foreign key in the employee table referencing the client_code of the client table, so you can only use client_code values that already exist in the client table.
I don't know what the structure of the create_client table looks like and what its purpose is, but based on your info I assume that you should first insert the data in client, then in employee and finally in create_client, so that every foreign key's value exists in its respective table.
If this is not correct, please post your table structures and the data or queries that could be causing this.
Edit after your comment: I assume that your table structure looks like this:
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`),
CONSTRAINT `client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `create_client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
However, I would suggest to use client as the parent table and move the foreign key constraint to create_client, so that both employee and create_client have a foreign key of client. I would also like to normalise this and get rid of company_name in the child tables:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`),
CONSTRAINT `create_client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
The next improvement would be to use the employee table for both unique and non-unique client_code inserts. Instead of using 2 identical tables, apart from the unique key, you could do the unique validation in Yii instead of in MySQL. You can specify the table name in the tableName() method of the CreateClient model . This will remain:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This should allow you to use the dynamic form, with Client as the main model and Employee as the items model.
On Yii2 using IO Generator (Model) and MySQL I have found the following.
I have seen SET '' instead of SET NULL in update SQL statement(s) on field(s) with foreign key constraints that have caused a "Integrity constraint violation".
My "fix" is to add a default rule on the foreign key field in the model, like so:
public function rules()
{
return [
//
// your other rules
//
[['field_name_with_foreign_key'], 'default', 'value' => null],
];
}
Hope this helps someone.
remove all foreign key checks and simplify database.
the problem lies in your foreign key structure.
learn carefully about primary keys and foreign keys.
make new database again without foreign keys then check.

Grocery Crud - CodeIgniter relation_n_n error

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

Red bean php R::getAll doesn't return any records

Here is database structure, generated with red bean php:
CREATE TABLE `attrib` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`type` tinyint(3) unsigned DEFAULT NULL,
`value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10 ;
CREATE TABLE `attrib_photo` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`attrib_id` int(11) unsigned DEFAULT NULL,
`photo_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UQ_e472845bf988796e2d3eceb91e2745b95f3aa534` (`attrib_id`,`photo_id`),
KEY `index_for_attrib_photo_attrib_id` (`attrib_id`),
KEY `index_for_attrib_photo_photo_id` (`photo_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=19 ;
CREATE TABLE `photo` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`filepath` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`date` set('1') COLLATE utf8_unicode_ci DEFAULT NULL,
`iscolored` tinyint(3) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;
ALTER TABLE `attrib_photo`
ADD CONSTRAINT `attrib_photo_ibfk_1` FOREIGN KEY (`attrib_id`) REFERENCES `attrib` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `attrib_photo_ibfk_2` FOREIGN KEY (`photo_id`) REFERENCES `photo` (`id`) ON DELETE CASCADE;
I'm making manually constructed query:
output of R::debug(); R::getAll($sql);
select filepath
from photo
inner join attrib as attrib4 on attrib4.type = 4 and attrib4.value in ("Dmitry")
inner join attrib_photo as attrib_photo4 on attrib_photo4.attrib_id = attrib4.id and attrib_photo4.photo_id = photo.id WHERE 1=1 LIMIT 0,25
Array ( )
resultset: 0 rows
[]
The result set is empty, but the base contains records, which fall under requirements, and running sql manually in phpMyAdmin shows them.
What's the problem with query, are there any additional debug info I can deal with to solve the problem? Thanks.
Update:
A little detail was missing, in original query I used unicode string for photo attribute search. After some investigations I found that php code works correctly and wrong encoding conversion happens on mysql side. Decision was to change collation of whole database to utf8_unicode_ci. Thanks for attention, and sorry for missing info in question.

Kohana orm inheritance

I want to auto creating parent record on creating children.
Example.
CREATE TABLE IF NOT EXISTS `front_end_users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userid` int(11) unsigned NOT NULL,
`tel` varchar(20) NOT NULL,
`addr1` varchar(255) NOT NULL,
`addr2` varchar(255) NOT NULL,
`city` int(11) NOT NULL,
`zip` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_userid` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(127) NOT NULL,
`username` varchar(32) NOT NULL DEFAULT '',
`password` char(64) NOT NULL,
`logins` int(10) unsigned NOT NULL DEFAULT '0',
`last_login` int(10) unsigned DEFAULT NULL,
`reset_token` char(64) NOT NULL DEFAULT '',
`status` varchar(20) NOT NULL DEFAULT '',
`last_failed_login` datetime NOT NULL,
`failed_login_count` int(11) NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_username` (`username`),
UNIQUE KEY `uniq_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `promouter` (
`userid` int(10) unsigned NOT NULL,
`balance` float NOT NULL,
`commision` float NOT NULL,
`mountly_fee` float NOT NULL,
`verified` tinyint(1) NOT NULL DEFAULT '0',
KEY `promouter_ibfk_1` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `front_end_users`
ADD CONSTRAINT `front_end_users_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE CASCADE;
ALTER TABLE `promouter`
ADD CONSTRAINT `promouter_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `front_end_users` (`userid`) ON DELETE CASCADE;
users->front_end_users->promouter
I want if I create promouter with login, password and address than automatically inserts appropriate fields in users (login, password), front_end_users (addr1, addr2, userid) and promouter (userid).
And I have several roles. So I can not add have_one to user model. But I added have_one to front_end_users and promouter models.
If you want to trigger parent creation on child creation then I think you should use trigger(s) on database level.
EDIT:
Create a table with the following scheme:
Rules(ID, TableName, ColumnName, Event, Action, Parameters)
You will have a set of Rules then and you will be able to make a general implementation for this. In your business layer you will call your rule parser (which also has to be implemented by you) and this way you can make any logical triggers in your business layer. I hope this helps.

Categories