Field 'foreign key' doesn't have a default value - mysql

I developed my backend using nodeJS and MySQL, which I have three tables as below :
Fournisseurs:
CREATE TABLE fournisseurs (
Codef bigint(21) NOT NULL ,
Noment varchar(20) COLLATE utf8_unicode_ci NOT NULL,
Prenomf varchar(20) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (Codef, Prenomf)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Categorie :
CREATE TABLE categorie (
Idcat bigint(21) NOT NULL AUTO_INCREMENT,
Nomcat varchar(20) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (Idcat, Nomcat)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Produits :
CREATE TABLE produits (
Codep bigint(21) NOT NULL AUTO_INCREMENT,
Reference bigint(21) NOT NULL,
Nomp varchar(20) COLLATE utf8_unicode_ci NOT NULL ,
Codef bigint(21) NOT NULL ,
Prenomf varchar(20) COLLATE utf8_unicode_ci NOT NULL,
Idcat bigint(21) NOT NULL ,
Nomcat varchar(20) COLLATE utf8_unicode_ci NOT NULL,
Description varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (Codep ),
FOREIGN KEY (Codef, Prenomf) REFERENCES fournisseurs (Codef, Prenomf)
ON DELETE CASCADE
ON UPDATE CASCADE ,
FOREIGN KEY (Idcat, Nomcat) REFERENCES categorie (Idcat, Nomcat)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10;
I try to insert into Produits table as you see below :
exports.ajouterprod = function(req, res) {
console.log("req", req.body);
var today = new Date();
var produits = {
"Reference": req.body.Reference,
"Nomp": req.body.Nomp,
// "Codef": req.body.Codef,
"Prenomf": req.body.Prenomf,
//"Idcat": req.body.Idcat,
"Nomcat": req.body.Nomcat,
"Description": req.body.Description
}
connection.query('INSERT INTO produits SET ?', produits, function(error, results, fields) {
if (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
else {
res.send({
"code": 200,
"success": "produit registered sucessfully"
});
}
})
};
when I run it with Postman, I get : "failed": "error ocurred"
and error ocurred { Error: ER_NO_DEFAULT_FOR_FIELD: Field 'Codef' doesn't have a default value on my backend.
As you see Codef is a primary key on my table fournisseurs.
How can I fix that ?

Why this error:
Since you are inserting data to Produits and not specifying any value Codef, this error is generated as foreign key needs a value(can be null as well)
Solution 1:
Alter table structure of Produits to have some default value that is either present in another table(where foreign key is referenced) or a null value.
Solution 2:
Add some default at code level and same in table where foreign key is referenced.

Related

Duplicate key entry when updating object

I have a Product object that has multiple Shop objects because a shop can offer the same product at different prices / conditions.
I have an edit view for the products that lists the shops where the product is available.
When I make adjustments to the shops of the product eg. price; I get the error that the shop already exists in the database. I know the product exists, but I need the data to be updated.
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 'PRIMARY'
public function update(Request $request, $slug)
{
$product = Product::with('shops', 'type')->where('slug', $slug)->first();
[... snip ...]
$i = 0;
foreach($product->shops as $shop) {
$shop = request('shop');
$product->shops()->attach($product->id, [
'shop_id' => $shop[$i]['id'],
'price' => $shop[$i]['price'],
'url' => $shop[$i]['url']
]);
$i++;
}
$product->save();
return redirect('/'.$slug)->with('success', 'Product has been updated');
}
$product->update(); yields the same result.
EDIT:
Product.php
class Product extends Model
{
protected $appends = ['lowest_price'];
public function shops(){
return $this->belongsToMany('App\Shop')->withPivot('price','url');
}
public function type(){
return $this->belongsTo('App\Type');
}
public function getLowestPriceAttribute()
{
$lowest_price = NULL;
foreach($this->shops as $shop) {
if(is_null($lowest_price)) {
$lowest_price = (double)$shop->pivot->price;
}
if($lowest_price > (double)$shop->pivot->price) {
$lowest_price = (double)$shop->pivot->price;
}
}
return $lowest_price;
}
}
Shop.php
class Shop extends Model
{
//
}
Shop migration
public function up()
{
Schema::create('shops', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('url');
$table->string('logo');
$table->timestamps();
});
[... snip ...]
}
EDIT2:
More info about the error:
Illuminate \ Database \ QueryException (23000)
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 'PRIMARY' (SQL: insert into `product_shop` (`price`, `product_id`, `shop_id`, `url`) values (500.00, 1, 1, http://test.com))
'CREATE TABLE `products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`make` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`model` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`video` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`manufacturer_specs` text COLLATE utf8_unicode_ci NOT NULL,
`top_speed` decimal(8,1) NOT NULL,
`range` decimal(8,1) NOT NULL,
`weight` decimal(8,1) NOT NULL,
`type_id` int(10) unsigned NOT NULL,
`slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`lowest_price` decimal(8,1) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `products_slug_unique` (`slug`),
KEY `products_type_id_index` (`type_id`),
CONSTRAINT `products_type_id_foreign` FOREIGN KEY (`type_id`) REFERENCES `types` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
'CREATE TABLE `product_shop` (
`product_id` int(10) unsigned NOT NULL,
`shop_id` int(10) unsigned NOT NULL,
`price` decimal(8,2) NOT NULL,
`url` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`product_id`,`shop_id`),
KEY `product_shop_product_id_index` (`product_id`),
KEY `product_shop_shop_id_index` (`shop_id`),
CONSTRAINT `product_shop_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE,
CONSTRAINT `product_shop_shop_id_foreign` FOREIGN KEY (`shop_id`) REFERENCES `shops` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
'CREATE TABLE `shops` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`logo` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
Edit3:
If I click the update button, I get the error even if I didn't change anything
You are trying to add another product-to-shop relation with the same keys, that's why you are seeing the index violation.
Instead of using attach, you can use sync:
$product->shops()->sync(
[
$shop[$i]['id'] => [
'price' => $shop[$i]['price'],
'url' => $shop[$i]['url']
]
], false);
The important part is the second parameter, which disabled detaching the other related items.
You could also use syncWithoutDetaching.
For details see:
Docs
Api

Foreign Key not adding in while doing alter table?

Here is my users.sql file :
CREATE TABLE users (
'id' bigint(20) NOT NULL auto_increment,
'md5_id' varchar(200) collate latin1_general_ci NOT NULL default '',
'user_name' varchar(200) collate latin1_general_ci NOT NULL default '',
'user_email' varchar(220) collate latin1_general_ci NOT NULL default '',
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
AUTO_INCREMENT=55 ;
Here id is the primary key.
Now this is the second table notifications.sql:
CREATE TABLE 'notifications' (
'notificationid' int(11) NOT NULL,
'creation_date_time' varchar(30) NOT NULL,
'view_date_time' varchar(30) NOT NULL,
'user_id bigint(big) NOT NULL,
'notification_text' varchar(255) NOT NULL,
'is_viewed' varchar(3) NOT NULL
)
Now when i try to add id in notifications table as foreign key it gives 1215 error. I don't know where i am going wrong.
This is my alter table code:
ALTER TABLE 'notifications'
ADD FOREIGN KEY (id) REFERENCES users(id)
ON DELETE CASCADE ON UPDATE CASCADE
You have to add the engine,charste and collate information to the second table too:
CREATE TABLE 'notifications' (
'notificationid' int(11) NOT NULL,
'creation_date_time' varchar(30) NOT NULL,
'view_date_time' varchar(30) NOT NULL,
'user_id bigint(big) NOT NULL,
'notification_text' varchar(255) NOT NULL,
'is_viewed' varchar(3) NOT NULL
)
ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
Also your table notifications ha no column id. You have to add this first and Name it user_id:
ALTER TABLE 'notifications'
ADD Column user_id int(11);
ALTER TABLE 'notifications'
ADD FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE ON UPDATE CASCADE

MySql - Sequalize - Cannot add foreign key constraint

I am trying to using Nodejs sequelize to create database. The commands being invoked are
CREATE TABLE IF NOT EXISTS `wheel` (`id` INTEGER NOT NULL auto_increment , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `shopId` VARCHAR(255), PRIMARY KEY (`id`),
FOREIGN KEY (`shopId`) REFERENCES `shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `segments` (`segmentID` VARCHAR(255) NOT NULL , `heading` VARCHAR(255) NOT NULL, `subHeading` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `wheelId` INTEGER, PRIMARY KEY (`segmentID`),
FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `shop` (`id` VARCHAR(255) NOT NULL , `accessToken` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
But I get this error
Unhandled rejection SequelizeDatabaseError: ER_CANNOT_ADD_FOREIGN:
Cannot add foreign key constraint
When I try to see the last foreign key error , it says
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-07-28 19:23:21 0x700000d95000 Error in foreign key constraint of table exitpopup/segments:
FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB:
Cannot resolve table name close to:
(`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB
Strangely, When I put the sql statements in sql console , it works and there isn't any error.
What am I doing wrong ?
The order needs to change. You are creatig the wheel table before you have created the shop table. However wheel refers to the shop table which does not exists in your original set of queries. When you change the order the shop table already exists so the error does not occur.
CREATE TABLE IF NOT EXISTS `shop`
(`id` VARCHAR(255) NOT NULL , `accessToken` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `wheel`
(`id` INTEGER NOT NULL auto_increment , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `shopId` VARCHAR(255),
PRIMARY KEY (`id`),
FOREIGN KEY (`shopId`) REFERENCES `shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `segments`
(`segmentID` VARCHAR(255) NOT NULL , `heading` VARCHAR(255) NOT NULL, `subHeading` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `wheelId` INTEGER,
PRIMARY KEY (`segmentID`),
FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
If you need to turn off this check, because you're importing a bunch of tables from a dump from another DB, you want to run:
set FOREIGN_KEY_CHECKS=0
As if it was a SQL statement. So for me in Sequelize I ran:
let promise = sequelize.query("set FOREIGN_KEY_CHECKS=0");
This is because of mainly following 2 reasons
1. When the primary key data type and the foreign key data type did not match.
return sequelize.define('Manager', {
id: {
type: DataTypes.INTEGER(11), // The data type defined here and
references: {
model: 'User',
key: 'id'
}
}
}
)
return sequelize.define('User', {
id: {
type: DataTypes.INTEGER(11), // This data type should be the same
}
}
)
2. When the referenced key is not a primary or unique key.
return sequelize.define('User', {
id: {
primaryKey: true
},
mail: {
type: DataTypes.STRING(45),
allowNull: false,
primaryKey: true // You should change this to 'unique:true'. you cant have two primary keys in one table.
}
}
)
It's possible your char encoding is different between the foreign key and the original key. Check your schema.
Declare your foreign key like this.
class Team extends Model {
static associate({ Player }) {
this.hasMany(Player, { foreignKey: 'playerId', onDelete: 'CASCADE' });
}
}
class Player extends Model {
static associate({ Team }) {
this.belongsTo(Team, {foreignKey: 'playerId', onDelete: 'CASCADE', targetKey: 'id',
});
}
}
The onDelete: 'CASCADE' is important.

Can't insert new row in cakephp 3.0

I am not able to insert a new row in table and getting the error
2016-04-12 09:23:54 Error: [RuntimeException] Cannot insert row in
"table_name" table, it has no primary key. Request URL:
I am using ORM and my code given below
$entityTable = TableRegistry::get('TableName');
$entity = $entityTable->newEntity();
$entity->name = 'Test Name';
$entity->image = 'test.png';
$entity->type = 1;
if($entityTable->save($entity)) {
$this->Flash->success('Added successfully.');
} else {
$this->Flash->error('Error!.');
}
And my table is
CREATE TABLE `table_name` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`image` text COLLATE utf8_unicode_ci NOT NULL,
`type` int(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
add $this->primaryKey('id');
in src>>Model>>Table>>TableNamesTable...
in your initialize method

Cannot add foreign key constraint when value is NULL?

I using CodeIgniter for develop my application, I have insert a constraint for this table:
Appointments
CREATE TABLE IF NOT EXISTS `appointments` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`GroupID` int(11) NOT NULL,
`book_datetime` datetime DEFAULT NULL,
`start_datetime` datetime DEFAULT NULL,
`end_datetime` datetime DEFAULT NULL,
`notes` text,
`hash` text,
`is_unavailable` tinyint(4) DEFAULT '0',
`guid_users_provider` char(36) DEFAULT NULL,
`guid_users_customer` char(36) DEFAULT NULL,
`guid_services` char(36) DEFAULT NULL,
`id_google_calendar` text,
`resources_guid` char(36) DEFAULT NULL,
`data` int(11) NOT NULL,
`lastUpdated` varchar(36),
PRIMARY KEY (`id`),
KEY `guid_users_customer` (`guid_users_customer`),
KEY `guid_services` (`guid_services`),
KEY `guid_users_provider` (`guid_users_provider`),
KEY `resources_guid` (`resources_guid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Resources
CREATE TABLE IF NOT EXISTS `resources` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`GUID` char(36) NOT NULL UNIQUE,
`descrizione` varchar(255) NOT NULL,
`sigla` varchar(255) NOT NULL,
`planning` varchar(255) NOT NULL,
`hex_color` varchar(255) NOT NULL,
`data` int(11) NOT NULL,
`lastUpdated` varchar(36),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
This is the constraint:
ALTER TABLE `appointments`
ADD CONSTRAINT `appointments_ibfk_5` FOREIGN KEY (`resources_guid`) REFERENCES `resources` (`GUID`) ON DELETE CASCADE ON UPDATE CASCADE;
The schema is builded correctly, but the problem is when I try to insert a record through my application, in particular the field resource_guid sometimes is NULL. Now, if I insert a record in PhpMyAdmin for test, in the appointments table and set the resource_guid as empty the record is added succesfully, but when I insert the record from my application on CodeIgniter I get this error:
Cannot add or update a child row: a foreign key constraint fails (scheduler.appointments, CONSTRAINT appointments_ibfk_5 FOREIGN KEY (resources_guid) REFERENCES resources (GUID) ON DELETE CASCADE ON UPDATE CASCADE)\",\"previous\":null,\
Now this is the content array of the query:
array(12) {
["guid_users_provider"]=>
string(36) "EE36D621-5E29-4674-81CB-B98622153E0C"
["start_datetime"]=>
string(19) "2015-12-30 23:19:00"
["end_datetime"]=>
string(19) "2015-12-31 00:45:00"
["notes"]=>
string(0) ""
["resources_guid"]=>
string(4) "null"
["is_unavailable"]=>
bool(false)
["guid_users_customer"]=>
string(36) "CDB8C010-7E51-4478-A341-F077E0460C88"
["guid_services"]=>
string(36) "31C40686-D72C-4361-B211-DCB2223552A9"
["book_datetime"]=>
string(19) "2015-12-31 01:12:39"
["hash"]=>
string(32) "5a9882faec12ab5bacb3445382176463"
["lastUpdated"]=>
string(27) "31-12-2015 10:12:39.5659760"
["GroupID"]=>
int(1)
}
How you can see the field resource_guid is NULL. Now the thing that I don't understand is (If I insert this in PhpMyAdmin as resource_guid set to NUll, so empty field, no error will be displayed, also from my application the error above appear).
This array is passed to the insert method of CodeIgniter like this:
if(!$this->db->insert('appointments', $appointment))
{
throw new Exception("Can't add record=> " . $this->db->_error_message());
}
How I can insert the resource also when is NULL? I mean, in my db table structure there is no renstriction for null value, infact in the appointments table is set with DEFAULT NULL. Someone could help me?
In your Appointments Table, you have given default value as NULL
Instead, give empty value as DEFAULT.
resources_guid` char(36) NOT NULL DEFAULT ''
To make an Existing Column as NOT NULL use MODIFY
ALTER TABLE Appointments MODIFY resources_guid char(36) NOT NULL DEFAULT ''
Look at your input resources_guid
["resources_guid"]=> string(4) "null"
It's a string with value "null", not a boolean NULL.
Pls check how you created that input. Make sure that is returning an actual NULL value. If you don't have control on that, you may need to change it manually by this way: (assuming the array as $appointment)
if($appointment["resources_guid"] == "null") {
$appointment["resources_guid"] = NULL;
}
Regarding the FOREIGN KEY, it should work as you have set it. There should be no problem for NULL values in the child field (unless the field is set as NOT NULL).