Duplicate key entry when updating object - mysql

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

Related

Laravel 7 leftJoin, Distinct and Sorted by related created_at

I'm developing a listing ads website dedicated to used video games with Laravel 7. I've got a 'GAMES' table and a 'LISTINGS' table as such.
GAMES
CREATE TABLE `games` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`title` text COLLATE utf8mb4_unicode_ci NOT NULL,
`slug` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `fulltext_index` (`title`)
) ENGINE=InnoDB AUTO_INCREMENT=10230 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
LISTINGS
CREATE TABLE `listings` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`game_id` bigint(20) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `listings_user_id_foreign` (`user_id`),
KEY `listings_game_id_foreign` (`game_id`),
CONSTRAINT `listings_game_id_foreign` FOREIGN KEY (`game_id`) REFERENCES `games` (`id`) ON DELETE CASCADE,
CONSTRAINT `listings_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=412 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
I need to have a paginated list of all the 'GAMES' (not listings) that are being sorted by the 'created_at' column of the latest 'LISTING' attached.
Thanks to #mayankmodi who helped sloving one of the problem, I've updated the below's part to focus on the sorting issue.
If I do this in my gameController:
$games = Game::leftJoin('listings', function($leftJoin)
{
$leftJoin->on('listings.game_id', 'games.id')
->whereNull('listings.deleted_at');
})
->select('games.*', 'listings.created_at')
->orderByDesc('listings.created_at')
->groupBy('games.id')
->with(['listings' => function ($query) {
$query->latest();
}])
->simplePaginate(36);
My games are distincts, but not ordered by last attached listing.created_at.
Do you have any idea how to solve this ?
Ok, I got it to work as expected.
Should anyone can benefit from 4+ hours of trying things out, I'll paste my solution down here.
$games = Game::leftJoin('listings', function($leftJoin){
$leftJoin->whereNull('listings.deleted_at')
->on('listings.game_id', 'games.id');
})
->select('games.*', DB::raw('MAX(listings.id) AS latest_listing'))
->groupBy('games.id')
->orderByDesc('latest_listing')
->with('listings')
->simplePaginate(36);
Thanks for your help !

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

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.

MySQL 1215 Cannot add foreign key constraint - Laravel 5

I'm stuck with this infamous error and can't figure out what went wrong. I'm trying to establish relationship between two tables orders and payments, whose migrations are defined as:
class CreateOrdersTable extends Migration
{
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('customer_id')->unsigned();
$table->integer('partner_id')->unsigned();
$table->string('status', 20)->default(Order::getDefaultStatus());
$table->string('paid', 20)->default('no');
$table->decimal('visitation_charges', 20, 2)->default(0);
$table->decimal('taxes', 20, 2)->default(0);
$table->decimal('charges', 20, 2)->default(0);
$table->decimal('discount', 20, 2)->default(0);
$table->decimal('total', 20, 2)->default(0);
$table->foreign('customer_id')->references('id')
->on('customers')->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('partner_id')->references('id')
->on('partners')->onDelete('cascade')
->onUpdate('cascade');
});
}
public function down()
{
Schema::dropIfExists('orders');
}
}
class CreatePaymentsTable extends Migration
{
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('order_id')->unsigned();
$table->string('gateway', 100);
$table->string('transaction_id', 100);
$table->decimal('amount', 20, 2);
$table->string('status', 20)->default(Payment::getDefaultStatus());
$table->string('comments', 2000)->nullable();
$table->foreign('order_id')->references('id')
->on('orders')->onDelete('set null')
->onUpdate('cascade');
});
}
public function down()
{
Schema::dropIfExists('payments');
}
}
The error I get is:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `payments` add constraint `payments_order_id_foreign` foreign key (`order_id`) references `orders` (`id`) on delete set null on update cascade)
I've also verified that the table engines, column types, character set, etc., are the same (following are the outputs of show create):
| orders | CREATE TABLE `orders` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`customer_id` int(10) unsigned NOT NULL,
`partner_id` int(10) unsigned NOT NULL,
`status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'created',
`paid` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no',
`visitation_charges` decimal(20,2) NOT NULL DEFAULT '0.00',
`taxes` decimal(20,2) NOT NULL DEFAULT '0.00',
`charges` decimal(20,2) NOT NULL DEFAULT '0.00',
`discount` decimal(20,2) NOT NULL DEFAULT '0.00',
`total` decimal(20,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`),
KEY `orders_customer_id_foreign` (`customer_id`),
KEY `orders_partner_id_foreign` (`partner_id`),
CONSTRAINT `orders_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `orders_partner_id_foreign` FOREIGN KEY (`partner_id`) REFERENCES `partners` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
| payments | CREATE TABLE `payments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`order_id` int(10) unsigned NOT NULL,
`gateway` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`transaction_id` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`amount` decimal(20,2) NOT NULL,
`status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pending',
`comments` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
Not sure where I'm going wrong. :/
You can't make a foreign key ON DELETE SET NULL for columns declared as NOT NULL.
The column can't be NULL.
The foreign key works if you do either of the following:
Omit the ON DELETE SET NULL:
alter table `payments` add constraint `payments_order_id_foreign`
foreign key (`order_id`) references `orders` (`id`) on update cascade;
Modify the column to allow NULL:
alter table payments modify order_id int(10) unsigned null;
Add nullable() on order_id column. Like below. Your error will be gone.
class CreatePaymentsTable extends Migration
{
public function up()
{
Schema::create('payments', function (Blueprint $table) {
// your others columns
$table->integer('order_id')->unsigned()->nullable();
}
}
it should better you build another migration for foreign key:
php artisan make:migration add_foreign_key_to_payment_table --table=payments
so add payments foreign key to this migration, then run php artisan migrate
if the error still exists you must drop manually orders and payments table and remove them from migration table then add those again.
I hope this will help you. Good day! :)

Mysql Laravel Constraint PRIMARY KEY MYSQL don't allowed

I have a simple table like that:
CREATE TABLE IF NOT EXISTS `dcp_type_discount` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`texte` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
And when i try to insert in another table a column foreign key to this table don't allow to me to do that.
In my local environement It is working.
But in my server i have an error like that
I am using laravel migration system and that is my migration :
public function up()
{
Schema::create('dcp_type_discount', function (Blueprint $table) {
$table->increments('id');
$table->string('code');
$table->string('texte');
$table->timestamps();
});
Schema::table('dcp_doc_item', function (Blueprint $table) {
$table->integer('type_remise_id')->nullable()->unsigned();
$table->foreign('type_remise_id')->references('id')->on('dcp_type_discount')->onDelete('cascade');
});
DB::table('dcp_type_discount')->insert(
[
[
'code' => '%',
'texte' => '%',
'created_at' => \Carbon\Carbon::now()->format('Y-m-d H:i:s')
],
[
'code' => 'UNIT',
'texte' => 'UNIT',
'created_at' => \Carbon\Carbon::now()->format('Y-m-d H:i:s')
]
]);
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('dcp_doc_item', function (Blueprint $table) {
$table->dropForeign(['type_remise_id']);
$table->dropColumn('type_remise_id');
});
Schema::drop('dcp_type_discount');
}
I think that the problem is not just because of laravel, because i tried in my PhpMyAdmin and when i try to add mannually an index on colonne type_remise_id, in the foreign column all primary key appear without this one.
I don't know what happen?!
Thanks to everybody.
PS: that is the decribe of my item table :
CREATE TABLE IF NOT EXISTS `dcp_doc_item` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`line` int(10) unsigned NOT NULL,
`material_id` int(10) unsigned NOT NULL,
`document_id` int(10) unsigned NOT NULL,
`quantity` double(8,2) NOT NULL,
`price_wo_vat` double(8,2) NOT NULL,
`vat` double(8,2) NOT NULL,
`discount` double(8,2) NOT NULL,
`net_price` double(8,2) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`price` double(8,2) DEFAULT NULL,
`qte_col` double(8,2) DEFAULT NULL,
`qte_colis` double(8,2) DEFAULT NULL,
`type_remise_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `dcp_doc_item_material_id_foreign` (`material_id`),
KEY `dcp_doc_item_document_id_foreign` (`document_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=85 ;

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row on CONSTRAINT `fk_users_has_ratings_businesses1

I'm getting this error when i try to insert new ratings
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yuldi`.`users_ratings`, CONSTRAINT `fk_users_has_ratings_businesses1` FOREIGN KEY (`business_id`) REFERENCES `businesses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
below database table structure with some foreign keys. i'm confused with adding multiple primary and foreign keys. please help me to sort out this issue
CREATE TABLE IF NOT EXISTS `yuldi`.`businesses` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`state` VARCHAR(100) NOT NULL,
`slug` VARCHAR(250) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`suburb` VARCHAR(100) NOT NULL,
`business_name` VARCHAR(100) NOT NULL,
`business_address` VARCHAR(250) NOT NULL,
`business_postal` VARCHAR(10) NOT NULL,
`business_postal_id` INT(11) NOT NULL,
`business_phone` VARCHAR(50) NOT NULL,
`business_phone1` VARCHAR(50) NOT NULL,
`business_phone2` VARCHAR(50) NOT NULL,
`business_email` VARCHAR(100) NOT NULL,
`business_website` VARCHAR(200) NOT NULL,
`business_details` VARCHAR(5000) NOT NULL,
`business_openinghours` VARCHAR(200) NOT NULL,
`business_service` VARCHAR(200) NOT NULL,
`business_addtionalinfo` VARCHAR(200) NOT NULL,
`business_lat` FLOAT(10,6) NOT NULL,
`business_lng` FLOAT(10,6) NOT NULL,
`identity` VARCHAR(100) NOT NULL,
`status` INT(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 232
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`ratings` (
`id` VARCHAR(36) NOT NULL,
`model` VARCHAR(255) NOT NULL,
`value` FLOAT(8,4) NULL DEFAULT '0.0000',
`comment` TEXT NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQUE_RATING` (`model` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_email` VARCHAR(255) NULL DEFAULT NULL,
`user_password` CHAR(100) NULL DEFAULT NULL,
`user_name` VARCHAR(255) NULL DEFAULT NULL,
`user_code` VARCHAR(255) NULL DEFAULT NULL,
`user_status` TINYINT(4) NULL DEFAULT '0',
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`ip_address` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 14
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users_ratings` (
`user_id` INT(11) NOT NULL,
`rating_id` VARCHAR(36) NOT NULL,
`business_id` INT(11) NOT NULL,
PRIMARY KEY (`user_id`, `rating_id`, `business_id`),
INDEX `fk_users_has_ratings_ratings1_idx` (`rating_id` ASC),
INDEX `fk_users_has_ratings_users1_idx` (`user_id` ASC),
INDEX `fk_users_has_ratings_businesses1_idx` (`business_id` ASC),
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_ratings1`
FOREIGN KEY (`rating_id`)
REFERENCES `yuldi`.`ratings` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_users1`
FOREIGN KEY (`user_id`)
REFERENCES `yuldi`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
The problem is coming from this:
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
The record you're trying to insert / update - probably user_ratings - is foreign keyed to the businesses table; you can't create a user_ratings record without a business_id, and that business_id must actually exist as an id in the businesses table.