Laravel sync throws integrity exception even if extist - mysql

I'm trying to link all my TicketMethod objects to all the Event objects:
foreach (Event::all() as $event) {
$event->ticketMethods()->attach([1, 2]);
}
The 1 and 2 are the only ids in the db for TicketMethod.
In my Event I have the following code:
public function ticketMethods()
{
return $this->belongsToMany('App\Models\TicketMethod', 'event_ticket_methods');
}
Exception:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails (`tickets`.`event_ticket_method
s`, CONSTRAINT `event_ticket_methods_event_id_foreign` FOREIGN KEY (`event_
id`) REFERENCES `events` (`id`) ON DELETE CASCADE) (SQL: insert into `event
_ticket_methods` (`event_id`, `ticket_method_id`) values (#/Y�� ���ʫB{�1�,
1), (#/Y�� ���ʫB{�1�, 2))
The event_id fields are in binary format, which causes the question marks.
I don't get the error, as the event exists as I just retrieved them...

Ended up by checking all my migrations. The event_id column got a different length than the id field in the events table.

Related

Laravel SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row

I want to delete a faculty but I have this error
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (trouverm_m_ecole.etablissement_filieres, CONSTRAINT etablissement_filieres_id_filieres_foreign FOREIGN KEY (id_filieres) REFERENCES filieres (id)) (SQL: delete from filieres where id = 1)
My migration
Schema::create('etablissement_filieres', function (Blueprint $table) {
$table->id();
$table->bigInteger('id_etablissements')->unsigned();
$table->foreign('id_etablissements')->references('id')->on('etablissements');
$table->bigInteger('id_filieres')->unsigned();
$table->foreign('id_filieres')->references('id')->on('filieres');
$table->string('prise_en_charge');
$table->string('prix');
$table->string('prix_affecte')->nullable();
$table->timestamps();
});
my controller
public function destroy($id)
{
Filiere::destroy($id);
return redirect('/tableau-de-bord/admin/dashboard/sindhost/toutes-les-filieres');
}
Any ideas ?
The problem is, there is a etablissement_filieres record referencing a record of filieres. Unless you have specified what to do when deleting a record refered by another record as a foreign key, it does not allow you to delete the foreign key record. Ideal way to handle this situation is to specify what to do when deleting a foreign key record. Check the Foreign Key Constraints of Laravel documentation to see the available options. Look at the section where it shows how to define the actions such as,
->onUpdate('cascade')
->onDelete('cascade');

Laravel Delete (Integrity Constraint Violation)

I'm trying to implement a delete on my controller but then I have this error:
Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`greatsup_wz`.`entryitems`, CONSTRAINT `entryitems_fk_check_entry_id` FOREIGN KEY (`entry_id`) REFERENCES `entries` (`id`)) (SQL: delete from `greatsup_wz`.`entries` where `id` = 686)
Here is a piece of my code:
$entryTable = DB::table(config("app.DB_ACCOUNTING").".entryitems")
->where('entryref_id','=',100)->get();
foreach($entryTable as $entryTbl):
DB::table(config("app.DB_ACCOUNTING").".entries")
->where('id','=',$entryTbl->entry_id)->delete(); // this is where my error occurred
endforeach;
How can I fix it ?
The constraints that you have added will prevent data from being deleted. You need to update database schema. You need to add onDelete('cascade') in the entryitems migration
Schema::create('tablename', function (Blueprint $table) {
$table->integer('columnName')->unsigned();
$table->foreign('columnName')->references('columnName')->on('relatedTableName')->onDelete('cascade');
});

Laravel - Can't solve Integrity constraint violation

I have created a new migration to add a column to an existing table and add a foreign key to an existing table.
This is the migration with the new column:
Schema::table( 'events', function ( Blueprint $table ) {
$table->integer( 'category_id' )->unsigned()->after( 'place_id' );
$table->foreign('category_id')->references('id')->on('categories');
} );
When I run the migrate command I get:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`meetmount`.`#sql-3c8_424`, CONSTRAINT `events_catego
ry_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: alter table `events` add constraint events_category_id_foreign foreign key (`category_id`) r
eferences `categories` (`id`))
and
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`meetmount`.`#sql-3c8_424`, CONSTRAINT `events_catego
ry_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))
How can I solve?
The cause of the error could be the following:
The parent table categories and/or the child table events already have records in them. As you want to reference the parent table's particular column (id), MySQL will expect the child table to have a value that exists in the parent, hence the integrity constraint violation.
A possible solution (in case the parent is not empty) is to add a default value in the events table for the foreign key column:
$table->integer( 'category_id' )->unsigned()->after( 'place_id' );
$table->foreign('category_id')->references('id')->on('categories')->default(1);
Happened the same with me, but I resolved this adding a default value on creation of column:
$table->integer( 'category_id' )->unsigned()->after( 'place_id' )->default(1);
Make sure the table "categories" has a record with id = 1.

Foreign Key Constraint in Laravel Migration

In Laravel 4, how can I add a foreign key constraint in a migration?
In the migration for mytable (which references foreigntable):
// add Column
$table
->string( 'foreigntable_id', 6 );
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
Error:
[Exception]
SQLSTATE[HY000]: General error: 1005 Can't create table 'mydb.#sql-1a24_2
1a' (errno: 150) (SQL: alter table `mytable` add constraint
mytable_foreigntable_id_foreign foreign key (`foreigntable_id`) references
`foreigntable` (`id`)) (Bindings: array (
))
I assume the problem is that foreigntable does not exist when MySQL tries to add the foreign key constraint to mytable (because the migration that creates foreigntable will only be run after the migration for mytable was finished).
How can I get around this problem?
Actually, I just found the answer myself.
Move the following from the migration for mytable into a new migration:
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
Since the new migration will be run after the migration for mytable, as well as after the migration for foreigntable, both tables will be present at the time that the foreign key constraints is added. Hence it works.

INSERT INTO... SELECT in same table generates foreign key error

I am having trouble with the following insert query.
INSERT INTO CM_LABEL_CALENDAR (
label_id,
label_name,
order_seq,
meal_id,
hyperlink
)
SELECT
label_id,
label_name,
order_seq,
(meal_id + 315),
hyperlink
FROM
CM_LABEL_CALENDAR
WHERE
(meal_id BETWEEN '1466' AND '1521');
When I try to execute it I get the following error:
Lookup Error - MySQL Database Error: Cannot add or update a child row: a foreign key constraint fails (TEST_PBMS.CM_LABEL_CALENDAR, CONSTRAINT CM_LABEL_CALENDAR_ibfk_1 FOREIGN KEY (meal_id) REFERENCES CM_MEAL_CALENDAR (meal_id))
I've tried looking for an answer but couldn't find one.
There is a foreign key constraint between CM_LABEL_CALENDAR(meal_id) and CM_MEAL_CALENDAR(meal_id)
You are getting this error because you are trying to insert values in the meal_id column that do not exist in the CM_MEAL_CALENDAR table.