Add foreign key in Yii migrations - php

I try to add foreign key to table, but when I run migration I getting this error:
General error: 1005 Can't create table 'chooseone.#sql-49a_49'
Its strange because chooseone is the name of my database. Here is how I try to add FK:
$this->addForeignKey('FK_user_profile', 'tbl_profile', 'user_id', 'tbl_user', 'id', 'CASCADE', 'CASCADE');
So what I am doing wrong?

I solve this issue. I change my definition of id column in tbl_user:
'id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
to
'id' => 'pk',
and all works properly.

Related

Alter table to Add default auto increment primary key 'id' in Phinx migration

I had created a table in a Phinx migration using
$table = $this->table('verification', ['id' => false, 'primary_key' => ['validation_id']]);
$table->addColumn('validation_id','string',['limit' => 15, 'null' => false])
->addColumn('status','string', ['null' => true])
>create();
Now in a separate migration I want to alter the table and set that id value to true and make that id as primary key (default behaviour). And make validation_id as a unique index.
I know how to do it by dropping the table first and creating new table. But I don't want to drop the table, just alter it. How to alter table to add back the auto increment default id column?

$wpdb->insert() throws "foreign key constraint fails" error

I have the following code:
$chck = $wpdb->insert( 'poruke_viber', array(
'id' => $data['message_token'],
'tekst' => $messageText,
'primljena' => '1',
'user_id' => $user['id'],
'vrijeme_epoch' => $data['timestamp']
));
logData($wpdb->last_error);
and it throws error:
Cannot add or update a child row: a foreign key constraint fails
It bugged me for couple of hours, I checked that I already have user_id in my parent table, and everything.
Until I tried replacing insert with query.
So when I did:
$wpdb->query('INSERT INTO poruke_viber (id, tekst, primljena, user_id, vrijeme_epoch)
VALUES ("'.$data['message_token'].'","'.$messageText.'","1","'.$user['id'].'","'.$data['timestamp'].'")');
It worked like a charm!
I'm here with the working code but not understanding what happened.
Is it wrong to use $wpdb->insert() on a table that has a foreign key?

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

I am using cakePHP framework in my web project,It seems many people have already ask similar question before.Even I try for those I couldn't find the answer.
Here is the error I got'
Database Error
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`fit_or_fat`.`disease_suggestions`, CONSTRAINT `disease_suggestions_ibfk_1` FOREIGN KEY (`disease_id`) REFERENCES `diseases` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Query: INSERT INTO `fit_or_fat`.`disease_suggestions` (`title`, `suggestion`, `disease_id`, `modified`, `created`) VALUES ('cholestorol', 'dddddddddddddddd', 'dd', '2014-08-24 00:04:32', '2014-08-24 00:04:32')
This is my model
'disease_id' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'disease_id must not be empty',
),
'custom' => array(
'rule' => '/[\w\s\d., \-_]+/',
'message' => 'user_id can only contain simple and capital letters, 0-9 numbers, . , - _ space and tabs only.',
),
),
You appear to be adding dd to the disease_id column. Which has a constraint. Most often ID columns are numerical. So this warning is telling you the the query is wrong, or specifically trying to insert values not allowed.
INSERT INTO `fit_or_fat`.`disease_suggestions` (`title`, `suggestion`, `disease_id`, `modified`, `created`) VALUES ('cholestorol', 'dddddddddddddddd', 1, '2014-08-24 00:04:32', '2014-08-24 00:04:32')
Will most likely be allowed (I have no idea what disease is on ID 1 but that's another issue all together).

yii migration return 1215 mysql error

After searching and checking my code over & over, now I want to ask.
I have 2 table umessage and ureply, when I want to add foreign key from ureply refrence to umessage I got 1215 mysql error.
Codes in file m140602_080318_create_table_umessage.php which create umessage table:
public function safeUp()
{
/*
* Create table umessage, this is connection way between customer & seller about specific object
* Add foreign key to table user and it's column id with sender column
* Add foreign key to table object and it's column id with objId column
*/
$this->createTable('tbl_umessage', array(
'id' => 'pk',
'time' => 'INT(15) NOT NULL',
'body' => 'TEXT NOT NULL',
'status' => 'TINYINT NOT NULL DEFAULT 0',
'visibleToS' => 'TINYINT NOT NULL DEFAULT 0',
'visibleToR' => 'TINYINT NOT NULL DEFAULT 0',
'sender' => 'INT(11)',
'objId' => 'INT(11) NOT NULL',
), 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci');
}
And codes in file m140602_080329_create_table_ureply.php which create ureply table:
public function safeUp()
{
/*
* Create table ureply which store all replies to exact message
* Add foreign key to table umessage and it's column id with msgId column
*/
$this->createTable('tbl_ureply', array(
'id' => 'pk',
'time' => 'INT(15) NOT NULL',
'body' => 'TEXT NOT NULL',
'isSender' => 'TINYINT NOT NULL DEFAULT 0',
'msgId' => 'INT(11) NOT NULL',
), 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci');
$this->addForeignKey('fk_ureply_umessage', 'tbl_ureply', 'msgId', 'umessage', 'id', 'CASCADE', 'CASCADE');
}
1215 error is for adding fk_ureply_umessage foreign key and I can't find my goofs.
Any help will be appreciated. thanks in advance.
You have a mistake in addForeignKey method:
$this->addForeignKey('fk_ureply_umessage', 'tbl_ureply', 'msgId', 'umessage', 'id', 'CASCADE', 'CASCADE');
the table that the foreign key references to should be tbl_umessage not umessage:
$this->addForeignKey('fk_ureply_umessage', 'tbl_ureply', 'msgId', 'tbl_umessage', 'id', 'CASCADE', 'CASCADE');
The error is related to foreign key references check the data type is equivalent between the foreign key and its reference

Yii Relations with non-Primary keys

I have a mysql table and a mysql view I'm trying to build relations for.
The table(commissions) is as follows:
--commissions--
id(primary Key)
date_added
order_id
salesrep_id
customer_id
commission_total
status
The view(rep_view_customer) is as follows:
--rep_view_customer--
entity_id
email
first_name
last_name
company
I'm trying to relate rep_view_customer to commissions on commissions.customer_id = rep_view_customer.entity_id.
I've tried using the on option:
'rep_view_customer' => array(self::HAS_ONE, 'RepViewCustomer', '', 'on'=>'rep_view_customer.entity_id = t.customer_id')
I also tried setting the primary key for the rep_view_customer model using:
public function primaryKey(){
return 'entity_id';
}
But I always seem to end up with an error similar to:
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]:
Column not found: 1054 Unknown column 't.customer_id' in 'where
clause'. The SQL statement executed was: SELECT
rep_view_customer.entity_id AS t1_c0,
rep_view_customer.email AS t1_c1,
rep_view_customer.first_name AS t1_c2,
rep_view_customer.last_name AS t1_c3,
rep_view_customer.company AS t1_c4 FROM rep_view_customer
rep_view_customer WHERE (rep_view_customer.entity_id =
t.customer_id)
I'm at my wit's end what to try next
You will have to create a foreign key inside repview_customer to relate to commissions. You won't be able to do it with just a primary key.
I did it this way and it works:
so in the commissions model you put: (it does the relation through itself within the model, then the join output will be the same as the normal relation but with other unique key in commission model)
public function relations()
{
return array(
'commission' => array(self::HAS_ONE, 'Commission', 'entity_id', 'on' => 'commission.customer_id=rep_view_customer.entity_id'),
'rep_view_customer' => array(self::HAS_MANY, 'RepViewCustomer', '', 'through' => 'commission', 'condition' => '...'),
),
}

Categories