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 ;
Related
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
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! :)
I have following structure on mysql database:
sqlfiddle
What I want to do is:
To select DISTINCT industry from Company table
To insert into Industry table first and get auto incremented ID
With this ID to insert again into IndustryTranslation table and set "language"="en"
To insert Company's id and newly generated Industry's id into MapCompanyIndustry table
I know that it's not possible with one statement. But definitely it's possible with transaction. Can't figure out how to achieve this result with one transaction.
Any suggestions?
Schema
CREATE TABLE `Industry` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `IndustryTranslation` (
`industryID` int(4) unsigned NOT NULL,
`language` varchar(5) NOT NULL,
`name` varchar(255) NOT NULL,
`confirmed` tinyint(1) DEFAULT '0',
PRIMARY KEY (`industryID`,`language`),
KEY `language` (`language`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `Company` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`imageUri` varchar(255) DEFAULT NULL,
`countryID` int(3) unsigned DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`verified` tinyint(1) DEFAULT NULL,
`industry` varchar(255) DEFAULT NULL,
`headquarters` varchar(255) DEFAULT NULL,
`uri` varchar(255) DEFAULT NULL,
`createdAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `countryID` (`countryID`)
) ENGINE=InnoDB AUTO_INCREMENT=4004 DEFAULT CHARSET=utf8;
CREATE TABLE `MapCompanyIndustry` (
`companyID` int(10) unsigned NOT NULL,
`industryID` int(4) unsigned NOT NULL,
PRIMARY KEY (`companyID`,`industryID`),
KEY `industryID` (`industryID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Mysql table is like
CREATE TABLE `User` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`telphone` varchar(32) NOT NULL,
`name` varchar(64) NOT NULL DEFAULT '',
`password` varchar(64) NOT NULL DEFAULT '',
`balance` int(11) NOT NULL DEFAULT '0',
`user_type` int(2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `phone_index` (`telphone`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
And the code I write is :
#Service
public class CommonDao {
#Resource
private DSLContext jooqContext;
public <R extends Record> R insertAndGet(Table<R> table, R r, Field<?>... f) {
return jooqContext.insertInto(table).set(r).returning(f).fetchOne();
}
}
It always return null when I use the insert and get, and the data actually insert into the database.
But When I delete the unique key in the mysql, It works fine.
I have a table which has does not have a primary key.Table has some indexes. Whenever I try to insert record for the first time ,record gets inserted successfully but when i try to insert record with same value again it gives Duplicate entry '125249-1'.
Create table :-
CREATE TABLE `schedules` (
`entity` bigint(20) DEFAULT NULL,
`id` bigint(20) DEFAULT NULL,
`applicationid` int(16) DEFAULT NULL,
`apptnid` int(16) DEFAULT NULL,
`apptorgunitid` bigint(20) DEFAULT NULL,
`orgid` int(16) DEFAULT NULL,
`nid` int(16) DEFAULT NULL,
`logged_date` datetime DEFAULT NULL,
`logged_by` int(16) DEFAULT NULL,
`last_updated_date` datetime DEFAULT NULL,
`last_updated_by` int(16) DEFAULT NULL,
`rowstate` int(8) DEFAULT '1',
`status` int(16) DEFAULT '1',
KEY `applicationid` (`applicationid`),
KEY `apptnid` (`apptnid`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into schedules (entity, id, applicationid, apptnid, apptorgunitid, orgid, nid, logged_date, logged_by, rowstate, status) values (125249,454,85246,2,2,124,1,current_timestamp,9999,1,1)
Error : - Duplicate entry '125249-1' for key 'PRIMARY'