I'm still new to understanding relationships and the MVC. But I tried to follow everything I've read online and still receives this error.
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`guest_log`.`logs`, CONSTRAINT `fk_logs_guests1` FOREIGN KEY (`guest_id`) REFERENCES `guests` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Here is the SQL for guest, log and department
DROP TABLE IF EXISTS `Dept`;
CREATE TABLE `Dept` (
`dept_id` int(5) NOT NULL AUTO_INCREMENT,
`dept_code` varchar(30) CHARACTER SET latin1 DEFAULT NULL,
`dept_description` varchar(75) CHARACTER SET latin1 NOT NULL,
`dept_assign` enum('Academic','Admin') CHARACTER SET latin1 NOT NULL DEFAULT 'Academic',
`is_deleted` enum('Yes','No') CHARACTER SET latin1 DEFAULT 'No',
PRIMARY KEY (`dept_id`)
)
-- ----------------------------
-- Table structure for guests
-- ----------------------------
DROP TABLE IF EXISTS `guests`;
CREATE TABLE `guests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`middle_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`last_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`gender` varchar(6) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`tel_no` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`mobile_no` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`company` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`photo` varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for logs
-- ----------------------------
DROP TABLE IF EXISTS `logs`;
CREATE TABLE `logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`guest_id` int(11) NOT NULL,
`guest_id_number` datetime NOT NULL,
`date_time_in` datetime NOT NULL,
`date_time_out` datetime DEFAULT NULL,
`purpose` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
`department_to_visit` int(11) DEFAULT NULL,
PRIMARY KEY (`id`,`guest_id`),
KEY `fk_logs_guests1_idx` (`guest_id`),
KEY `fk_logs_Dept1_idx` (`department_to_visit`),
CONSTRAINT `fk_logs_guests1` FOREIGN KEY (`guest_id`) REFERENCES `guests` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_logs_Dept1` FOREIGN KEY (`department_to_visit`) REFERENCES `Dept` (`dept_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
While here are the models.
class Guest extends Model
{
protected $table = 'guests';
public function logs()
{
return $this->hasMany('App\Log');
}
}
class Log extends Model
{
protected $table = 'logs';
public function guests()
{
return $this->belongsTo('App\Guest','guest_id','id');
}
public function departments()
{
return $this->belongsTo('App\Department','department_to_visit','dept_id');
}
}
class Department extends Model
{
protected $table = 'dept';
public function logs()
{
return $this->hasMany('App\Log','department_to_visit','dept_id');
}
}
Whenever I try to create a new entry for Log, I received this Integrity Constraint Violation error. Please help me resolved and understand why I'm encountering this problem.
UPDATE:
code to create log entry
<div class="container-fluid">
{!! BootForm::inline(['route'=>['logs.store'],'method'=>'POST']) !!}
{!! BootForm::select('guest_id', 'Guest Name',\App\Guest::pluck('last_name','id'),null, [])!!}
{!! BootForm::tel('guest_id_number','ID Number',null, ['required']) !!}
{!! BootForm::select('department_to_visit','Department to Visit', App\Department::pluck('dept_description','dept_id'),null,[]) !!}
{!! BootForm::text('purpose',null,null,['required']) !!}
{!! BootForm::submit('Save') !!}
{!! BootForm::close() !!}
</div>
log.store method
public function store(Request $request)
{
$this->validate($request, [
'guest_id'=>'required',
'guest_id_number'=>'required',
'purpose'=>'required',
'department_to_visit']);
$logs = new Log();
$logs->guest_id = $request->guest_id;
$logs->guest_id_number = $request->guest_id_number;
$logs->purpose = $request->purpose;
$logs->department_to_visit = $request->department_to_visit;
$logs->date_time_in = Carbon::now();
$logs->save();
return redirect(route('home'));
}
It could be you are not passing and existing guest id.
To check it normally I search the model, for eg.
$guest = Guest::findOrFail($request->guest_id);
and use
$logs->guest_id = $guest->id;
Try this and let me know how it works :)
Related
This is my t_complaint
CREATE TABLE `t_complaint` (
`idcomplaint` int(11) NOT NULL,
`tglterima` date DEFAULT NULL,
`dept` varchar(5) DEFAULT NULL,
`pengirim` varchar(255) DEFAULT NULL,
`kontak` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`telp` varchar(255) DEFAULT NULL,
`jenis` varchar(45) DEFAULT NULL,
`uraian` text,
`uniqueid` varchar(9) DEFAULT NULL,
`responder` varchar(245) DEFAULT NULL,
`tgljawab` date DEFAULT NULL,
`jawaban` text,
`status` varchar(45) DEFAULT NULL,
`tglclose` date DEFAULT NULL,
`createddate` datetime DEFAULT NULL,
`createdby` varchar(45) DEFAULT NULL,
`modifieddate` datetime DEFAULT NULL,
`modifiedby` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and this is t_complaint_detail:
CREATE TABLE `t_complaint_detail` (
`no` int(11) NOT NULL,
`uniqueid` varchar(9) DEFAULT NULL,
`uploader` varchar(100) DEFAULT NULL,
`st_uploader` int(11) DEFAULT NULL,
`file_upload` text,
`original_name` text,
`status` int(11) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
t_complaint.idcomplaint is a primary key with Auto Increment attribute
t_complaint_detail.no is a primary key with Auto Increment attribute
I'd like to connected these table via uniqueid
I've tried ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('uniqueid') REFERENCES t_complaint('uniqueid')
The query above gives error. The error is #1005 - Can't create tablebsm.#sql-890_730(errno: 150 "Foreign key constraint is incorrectly formed") (Details…)
bsm in the error is my database (my database is bsm)
Foreign key should must be a primary key in parent table. The question is, why you are adding a redundant 'uniqueId' in both the table? You can simply define a foreign key constraint like this :
t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('idcomplaint') REFERENCES t_complaint('idcomplaint').
It should work.
Error came like this
ERROR 1215 (HY000): Cannot add foreign key constraint
Because you need to create primary key in table.you can add primary key
like this
alter table t_complaint_detail modify uniqueid varchar(20) not null;
and
alter table t_complaint_detail modify uniqueid varchar(20) not null;
after it will be works
ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY (uniqueid) REFERENCES t_complaint(uniqueid);
please read here for more reference that will be help
It's working fine for me :
Try this :
ALTER TABLE t_complaint ADD CONSTRAINT t_complaint_detail
FOREIGN KEY ( uniqueid ) REFERENCES t_complaint( uniqueid )
Reference here :
https://www.w3schools.com/sql/sql_foreignkey.asp
This is my migration:
$table->increments('id');
$table->string('nombre1',255);
$table->string('nombre2',255)->nullable();
$table->string('apellido1',255)->nullable();
$table->string('apellido2',255)->nullable();
$table->string('apellido_casada',255)->nullable();
$table->string('cedula',255)->nullable();
$table->integer('entidad_id')->nulleable()->unsigned();
**$table->integer('cargo_id')->nulleable()->unsigned();
$table->integer('partido_id')->nulleable()->unsigned();
$table->integer('provincia_id')->nulleable()->unsigned();
$table->integer('distrito_id')->nulleable()->unsigned();
$table->integer('corregimiento_id')->nulleable()->unsigned();**
$table->string('otro_nombre',255)->nullable();
$table->dateTime('fecha_nacimiento')->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign('entidad_id')->references('id')->on('entidad');
$table->foreign('cargo_id')->references('id')->on('cargo');
$table->foreign('partido_id')->references('id')->on('partido');
$table->foreign('provincia_id')->references('id')->on('provincia');
$table->foreign('distrito_id')->references('id')->on('distrito');
$table->foreign('corregimiento_id')->references('id')->on('corregimiento');
When i run this migration the table generated is:
CREATE TABLE pep (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
nombre1 VARCHAR(255) COLLATE UTF8_UNICODE_CI NOT NULL,
nombre2 VARCHAR(255) COLLATE UTF8_UNICODE_CI DEFAULT NULL,
apellido1 VARCHAR(255) COLLATE UTF8_UNICODE_CI DEFAULT NULL,
apellido2 VARCHAR(255) COLLATE UTF8_UNICODE_CI DEFAULT NULL,
apellido_casada VARCHAR(255) COLLATE UTF8_UNICODE_CI DEFAULT NULL,
cedula VARCHAR(255) COLLATE UTF8_UNICODE_CI DEFAULT NULL,
**entidad_id INT(10) UNSIGNED NOT NULL,
cargo_id INT(10) UNSIGNED NOT NULL,
partido_id INT(10) UNSIGNED NOT NULL,
provincia_id INT(10) UNSIGNED NOT NULL,
distrito_id INT(10) UNSIGNED NOT NULL,
corregimiento_id INT(10) UNSIGNED NOT NULL,**
otro_nombre VARCHAR(255) COLLATE UTF8_UNICODE_CI DEFAULT NULL,
fecha_nacimiento DATETIME DEFAULT NULL,
created_at TIMESTAMP NULL DEFAULT NULL,
updated_at TIMESTAMP NULL DEFAULT NULL,
deleted_at TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (id),
KEY pep_entidad_id_foreign (entidad_id),
KEY pep_cargo_id_foreign (cargo_id),
KEY pep_partido_id_foreign (partido_id),
KEY pep_provincia_id_foreign (provincia_id),
KEY pep_distrito_id_foreign (distrito_id),
KEY pep_corregimiento_id_foreign (corregimiento_id),
CONSTRAINT pep_cargo_id_foreign FOREIGN KEY (cargo_id)
REFERENCES cargo (id),
CONSTRAINT pep_corregimiento_id_foreign FOREIGN KEY (corregimiento_id)
REFERENCES corregimiento (id),
CONSTRAINT pep_distrito_id_foreign FOREIGN KEY (distrito_id)
REFERENCES distrito (id),
CONSTRAINT pep_entidad_id_foreign FOREIGN KEY (entidad_id)
REFERENCES entidad (id),
CONSTRAINT pep_partido_id_foreign FOREIGN KEY (partido_id)
REFERENCES partido (id),
CONSTRAINT pep_provincia_id_foreign FOREIGN KEY (provincia_id)
REFERENCES provincia (id)
) ENGINE=INNODB DEFAULT CHARSET=UTF8 COLLATE = UTF8_UNICODE_CI;
The problem is that some of the columns: entidad_id, cargo_id, etc, are declared as NULL and when i set the FK, laravel created them as NOT NULL.
Is anyting here that i am missing??
Sorry for being late.
You have typos in code
nulleable
$table->integer('entidad_id')->nulleable()->unsigned();
should be
nullable
$table->integer('entidad_id')->nullable()->unsigned();
Don't know why Laravel is not yelling on typos :(
I have a basic symfony2 form where I can set a value for my field.
I've just figured out that null values where saved as empty strings, where I expect an exception to be raised because thenull value is not accepted.
My mapping (within a trait) :
/**
* #ORM\Column(name="name", type="string", length=100, nullable=false)
*/
protected $name;
My field :
->add('name', null, array(
'label'=>'Nom détaillé',
'required' => false))
Setting required to true and defining assert rules works well but here I'm trying to solve this conversion issue.
If I put a vardumpin the SetName method, I do get a null value which is later saved as an empty string in my database. How can I solve that ?
EDIT : the show create table t
CREATE TABLE `recipe` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`isProduct` tinyint(1) NOT NULL,
`portions` int(11) DEFAULT NULL,
`nickname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`shortDescription` varchar(500) COLLATE utf8_unicode_ci DEFAULT NULL,
`weight` decimal(10,2) DEFAULT NULL,
`isPrivate` tinyint(1) NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`slug` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`content` longtext COLLATE utf8_unicode_ci,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
`viewCount` int(11) NOT NULL,
`parentId` int(10) unsigned DEFAULT NULL,
`userId` int(10) unsigned DEFAULT NULL,
`createdBy` int(10) unsigned DEFAULT NULL,
`updatedBy` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_DD24B40110EE4CEE` (`parentId`),
KEY `IDX_DD24B40164B64DCC` (`userId`),
KEY `IDX_DD24B401D3564642` (`createdBy`),
KEY `IDX_DD24B401E8DE7170` (`updatedBy`),
CONSTRAINT `FK_DD24B40110EE4CEE` FOREIGN KEY (`parentId`) REFERENCES `recipe` (`id`) ON DELETE SET NULL,
CONSTRAINT `FK_DD24B40164B64DCC` FOREIGN KEY (`userId`) REFERENCES `user` (`id`),
CONSTRAINT `FK_DD24B401D3564642` FOREIGN KEY (`createdBy`) REFERENCES `user` (`id`) ON DELETE SET NULL,
CONSTRAINT `FK_DD24B401E8DE7170` FOREIGN KEY (`updatedBy`) REFERENCES `user` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Seems like you just need to add a strict equivalence check === against the variable and then throw new Exception() if it's null
I have a model like this:
<?php
class Post extends Eloquent {
protected $fillable = [];
public function photos()
{
return $this->morphMany('Upload', 'imageable');
}
public function attachments()
{
return $this->morphMany('Upload', 'attachable');
}
}
and my morphMany table's schema is like this:
CREATE TABLE `uploads` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`raw_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`size` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`downloads` int(11) NOT NULL DEFAULT '0',
`imageable_id` int(11) DEFAULT NULL,
`imageable_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`attachable_id` int(11) DEFAULT NULL,
`attachable_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `uploads_user_id_index` (`user_id`),
CONSTRAINT `uploads_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
now I need to remove one row of this table, I tried $posts->photos()->delete(); but it removed all rows associated to this Post.
Could someone help me?
$posts->photos() is the relationship query to return all of the photos for a post. If you call delete() on that, it will delete all of those records. If you only want to delete a specific record, you need to make sure you only call delete on the one you want to delete. For example:
$posts->photos()->where('id', '=', 1)->delete();
to reomove from pivot table in many to many polymorphic relation just use detach:
$posts->photos($photoModel)->detach();
The relationship isn't even needed for this. Just use the Upload model directly:
Upload::find($id)->delete();
Or even shorter:
Upload::destroy($id);
I'm working a project with Yiiframwork and I have this table in my data base project
CREATE TABLE IF NOT EXISTS `tbl_annonce` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`idEntreprise` tinyint(3) unsigned NOT NULL
COMMENT 'CONSTRAINT FOREIGN KEY (idEntreprise) REFERENCES tbl_entreprise(id)',
`titre` varchar(100) NOT NULL,
`detailleDiscription` varchar(5000) NOT NULL,
`categorie` varchar(100) DEFAULT NULL,
`typePoste` varchar(100) NOT NULL,
`salaireMin` varchar(80) NOT NULL,
`salaireMax` varchar(80) NOT NULL,
`niveauEtude` varchar(80) NOT NULL,
`niveauExperience` varchar(80) NOT NULL,
`langue` varchar(50) DEFAULT NULL,
`poste` varchar(50) NOT NULL,
`pays` varchar(50) NOT NULL,
`ville` varchar(50) NOT NULL,
`adresse` varchar(80) NOT NULL,
`datePublication` timestamp NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`etat` varchar(50) NOT NULL,
`photo` varchar(255) NULL,
`nometr` text NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_idEntrepriseAnn`
FOREIGN KEY (idEntreprise)
REFERENCES tbl_entreprise(id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
I only use 'comment' because I found it in a tutorial for a yii framework project.
I have got the attribute 'idEntreprise' as FK in my DB but when I entred other 'idEntreprise' that does note exist in my table entreprise it was not problem, instead it must be a problem.
So I added 'identreprise' as Fk and that have this problem now.
Hope you understand my problem :/
can any one helep me plz !!
To define a foreign key on a column, it must fulfil some conditions.
Child and parent column must have same column definition by type,
signed.
Parent column must have an index defined on it.
Make sure that
The column tbl_entreprise.id is indexed.
The column definition idEntreprise tinyint(3) unsigned in tbl_annonce matches
with that of tbl_entreprise.id
Refer to: MySQL: Foregin Key Constaints