Yii2 migration General error: 1215 Cannot add foreign key constraint - yii2

I created my tables like this:
$this->createTable('evenement', [
'id' => $this->integer(),
'description' => $this->string(),
'status' => $this->smallInteger()->defaultValue(10),
'start_datetime' => $this->integer()->notNull(),
'end_datetime' => $this->integer()->notNull()
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
'created_by' => $this->integer(),
'updated_by' => $this->integer(),
], $tableOptions);
$this->createTable('event_participant', [
'event_id' => $this->integer(),
'user_id' => $this->integer(),
'status' => $this->smallInteger()->defaultValue(10),
], $tableOptions);
$this->addPrimaryKey('pk-event_participant', 'event_participant', ['event_id', 'user_id']);
$this->addForeignKey('fk-user_id-event_participant', 'event_participant', 'user_id', 'user', 'id', 'no action');
$this->addForeignKey('fk-event_id-event_participant', 'event_participant', 'event_id', 'evenement', 'id', 'CASCADE');
But I getting this error and I do not know why? What am I doing wrong?
add foreign key fk-event_id-event_participant: event_participant (event_id) references evenement (id) ...Exception 'yii\db\Exception' with message 'SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
The SQL being executed was: ALTER TABLE `event_participant` ADD CONSTRAINT `fk-event_id-event_participant` FOREIGN KEY (`event_id`) REFERENCES `evenement` (`id`) ON DELETE CASCADE'

Foreign key can be linked only to primary or unique key.
Add PK or UK definition to evenement table
'id' => $this->primaryKey(),
or
'id' => $this->integer()->notNull()->unique(),

Related

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add laravel

I am getting this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(prj_tvto.activities, CONSTRAINT activities_school_id_foreign FOREIGN
KEY (school_id) REFERENCES schools (id)) (SQL: insert into activities
(school_id, cluster_id, group_id, updated_at, created_at) values (0,
2, 3, 2018-08-14 05:02:28, 2018-08-14 05:02:28))
In Controller
public function store(Request $request, SchoolsList $schoolsList)
{
if($request->ajax()) {
$activity = new Activity();
$activity->school_id = intval($request->school_id);
$activity->cluster_id = $request->cluster_id;
$activity->group_id = $request->group_id;
$activity->save();
return response()->json(['data_activity' => $request->all(), 'id' => $activity->id]);
}
}
And Ajax
var school_id = {school_id: data_school.id} ;
console.trace(school_id);
I am using laravel 5.4

Yii relation for composite key as foreign key and get sum

I have three tables (Booking,Ticket,Trainee_grant) with below structure
Booking
id (primary key)
name
Ticket
booking_id int,
seq int,
name
address,
primary key (booking_id,seq)
CONSTRAINT `fk_booking` FOREIGN KEY booking_id reference Booking
Trinee_Grant
id int
booking_id
seq
amount
CONSTRAINT `fk_trainne_ticket_grant` FOREIGN KEY (`booking_id`, `seq`) REFERENCES `ticket` (`booking_id`, `seq`) ;
I have relation for Ticket_tb and trainee_grant_tb as below.
Ticket model
public function relations() {
return array(
'booking' => array(self::BELONGS_TO, 'Booking', 'booking_id'),
'traineeGrants' => array(self::HAS_MANY, 'TraineeGrant', 'booking_id'),
'traineeGrants1' => array(self::HAS_MANY, 'TraineeGrant', 'seq'),
);
}
and TraineeGrant model as below
public function relations() {
return array(
'bookingSeq' => array(self::BELONGS_TO,'Ticket','booking_id,seq'),
);
}
How can i add relation in Booking so that i can get SUM(amount) of all booking_id from trainee_grant table ?
I tried with below but gives me error.
Booking Model
$relations['amountTraineeGrant'] = [
self::STAT,
'TraineeGrant',
'booking_id',
'select' => 'SUM(amount)',
];
it gives me error as below
The relation "amountTraineeGrant" in active record class "Booking" is specified with a foreign key "booking_id" that does not point to the parent table "booking".
Am i missing something ..i am not able to find error .Plz help me
I guess you are applying relationshiop rule in wrong model. It should be applied to model Trainee_grant.
Refer to this

Deleting foreign key in cakephp

I want to delete a record in database where it is a foreign key. The below code has been written for product table.
public function delete() {
$id = $this->request->params['pass'][0];
if( $this->Product->delete( $id )){
$this->Session->setFlash('Product was deleted');
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('Unable to delete product');
$this->redirect(array('action' => 'index'));
}
}
Now what should I do to delete it from master table also?
This is the error I'm getting:
Error: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`indianautogas1`.`agent_to_consumer`, CONSTRAINT `agent_to_consumer1_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`))
SQL Query: DELETE `Product` FROM `indianautogas1`.`products` AS `Product` WHERE `Product`.`id` = 1

A foreign key constraint fails with Zend_Db_Table

I have to tables and their SQL is as below:
CREATE TABLE item (
itemID INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
price FLOAT NOT NULL,
stock INTEGER NOT NULL
) ENGINE = InnoDB;
CREATE TABLE salesrecord (
recordID INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
itemID INT UNSIGNED NOT NULL,
recordDate DATE NOT NULL,
FOREIGN KEY (itemID) REFERENCES item (itemID)
) ENGINE = InnoDB;
And this is my Zend_Db_Table concrete classes:
<?php
class Store_Model_Items extends Zend_Db_Table_Abstract
{
protected $_name = 'item';
protected $_rowClass = 'Store_Model_Item';
protected $_dependTables = array('Store_Model_SalesRecords');
}
<?php
class Store_Model_SalesRecords extends Zend_Db_Table_Abstract
{
protected $_name = 'salesrecord';
protected $_referenceMap = array(
'Item' => array(
'columns' => array('itemID'),
'refTableClass' => 'Store_Model_Items',
'refColumns' => array('itemID'),
'onDelete' => self::CASCADE
)
);
}
When I try to delete a row in item table,
I get this message:
SQLSTATE[HY000]: General error: 1451 Cannot delete or update a parent row: a foreign key constraint fails (newstore/salesrecord, CONSTRAINT salesrecord_ibfk_1 FOREIGN KEY (itemID) REFERENCES item (itemID))
If you want delete the record from parent table, firstly you should delete related records in a child table. Also you can add ON DELETE CASCADE checking, it will help automatically delete related records in the child table. Try to recreate your FK in this way -
ALTER TABLE salesrecord
DROP FOREIGN KEY salesrecord_ibfk_1; -- change FK name here!
ALTER TABLE salesrecord
ADD CONSTRAINT salesrecord_ibfk_1 FOREIGN KEY (itemID)
REFERENCES item(itemID) ON DELETE CASCADE;
Change 'salesrecord_ibfk_1' with actual FK name.

Do I need to manually create indexes for a DBIx::Class belongs_to relationship

I'm using the DBIx::Class modules for an ORM approach to an application I have.
I'm having some problems with my relationships.
I have the following
package MySchema::Result::ClusterIP;
use strict;
use warnings;
use base qw/DBIx::Class::Core/;
our $VERSION = '1.0';
__PACKAGE__->load_components(qw/InflateColumn::Object::Enum Core/);
__PACKAGE__->table('cluster_ip');
__PACKAGE__->add_columns( # Columns here );
__PACKAGE__->set_primary_key('objkey');
__PACKAGE__->belongs_to( 'configuration' => 'MySchema::Result::Configuration', 'config_key');
__PACKAGE__->belongs_to( 'cluster' => 'MySchema::Result::Cluster',
{ 'foreign.config_key' => 'self.config_key',
'foreign.id' => 'self.cluster_id'
}
);
As well as
package MySchema::Result::Cluster;
use strict;
use warnings;
use base qw/DBIx::Class::Core/;
our $VERSION = '1.0';
__PACKAGE__->load_components(qw/InflateColumn::Object::Enum Core/);
__PACKAGE__->table('cluster');
__PACKAGE__->add_columns( # Columns here );
__PACKAGE__->set_primary_key('objkey');
__PACKAGE__->belongs_to( 'configuration' => 'MySchema::Result::Configuration', 'config_key');
__PACKAGE__->has_many('cluster_ip' => 'MySchema::Result::ClusterIP',
{ 'foreign.config_key' => 'self.config_key',
'foreign.cluster_id' => 'self.id'
});
There are a couple of other modules, but I don't believe that they are relevant.
When I attempt to deploy this schema, I get the following error:
DBIx::Class::Schema::deploy(): DBI Exception: DBD::mysql::db do failed: Can't create table 'test.cluster_ip' (errno: 150) [
for Statement "CREATE TABLE `cluster_ip` (
`objkey` smallint(5) unsigned NOT NULL auto_increment,
`config_key` smallint(5) unsigned NOT NULL,
`cluster_id` char(16) NOT NULL,
INDEX `cluster_ip_idx_config_key_cluster_id` (`config_key`, `cluster_id`),
INDEX `cluster_ip_idx_config_key` (`config_key`),
PRIMARY KEY (`objkey`),
CONSTRAINT `cluster_ip_fk_config_key_cluster_id` FOREIGN KEY (`config_key`, `cluster_id`) REFERENCES `cluster` (`config_key`, `id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `cluster_ip_fk_config_key` FOREIGN KEY (`config_key`) REFERENCES `configuration` (`config_key`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB"] at test_deploy.pl line 18
(running "CREATE TABLE `cluster_ip` (
`objkey` smallint(5) unsigned NOT NULL auto_increment,
`config_key` smallint(5) unsigned NOT NULL,
`cluster_id` char(16) NOT NULL,
INDEX `cluster_ip_idx_config_key_cluster_id` (`config_key`, `cluster_id`),
INDEX `cluster_ip_idx_config_key` (`config_key`),
PRIMARY KEY (`objkey`),
CONSTRAINT `cluster_ip_fk_config_key_cluster_id` FOREIGN KEY (`config_key`, `cluster_id`) REFERENC
ES `cluster` (`config_key`, `id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `cluster_ip_fk_config_key` FOREIGN KEY (`config_key`) REFERENCES `configuration` (`conf
ig_key`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB") at test_deploy.pl line 18
From what I can tell, MySQL is complaining about the FOREIGN KEY constraint, in particular, the REFERENCE to (config_key, id) in the cluster table. From my reading of the MySQL documentation, this seems like a reasonable complaint, especially in regards to the third bullet point on this doc page.
Here's my question. Am I missing something in the DBIx::Class module? I realize that I could explicitly create the necessary index to match up with this foreign key constraint, but that seems to be repetitive work. Is there something I should be doing to make this occur implicitly?
Not sure what is happening here as SQL::Translator::Producer::MySQL should insert SET foreign_key_checks=0 at the start of the deployed DDL so no foreign key errors should occur. I suspect something is broken even after the whole DDL is deployed. You can find out the exact nature of the foreign key error by connecting to the DB and running this statement:
SHOW INNODB STATUS;
I just fixed this same problem by adding the following into my result classes that were causing problems:
sub sqlt_deploy_hook {
my ($self, $sqlt_table) = #_;
$sqlt_table->add_index(name => 'idx_my_column', fields => ['my_column']);
}