Angular 7 : Cannot add or update a child row: a foreign key constraint fails

46
March 15, 2019, at 8:50 PM

I am stuck on this SQL error and I do not understand why:

SQL Table

CREATE DATABASE IF NOT EXISTS `cinego` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `cinego`;
-- Listage de la structure de la table cinego. salle
CREATE TABLE IF NOT EXISTS `salle` (
  `idSalle` int(11) NOT NULL AUTO_INCREMENT,
  `nom` varchar(50) DEFAULT NULL,
  `plan` blob,
  `nbPlace` int(11) DEFAULT NULL,
  `idCinema` int(11) DEFAULT NULL,
  `idTechno` int(11) DEFAULT NULL,
  PRIMARY KEY (`idSalle`),
  KEY `ref_salle_cinema` (`idCinema`),
  KEY `ref_salle_techno` (`idTechno`),
  CONSTRAINT `ref_salle_cinema` FOREIGN KEY (`idCinema`) REFERENCES `cinema` (`idCinema`),
  CONSTRAINT `ref_salle_techno` FOREIGN KEY (`idTechno`) REFERENCES `technologie` (`idTechno`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;

This is my table that is present in a DB Mysql.

Typescript

@Component({
  selector: 'app-room-add',
  templateUrl: './room-add.component.html',
  styleUrls: ['./room-add.component.scss']
})
export class RoomAddComponent implements OnInit {
  cinema: Cinema = new Cinema();
  techno: Techno = new Techno();
  cinemas: Cinema[] = [];
  technos: Techno[] = [];
  addRoomForm = new FormGroup({
    name: new FormControl(''),
    blueprint: new FormControl(''),
    placelenght: new FormControl(''),
    cinema: new FormControl(''),
    techno: new FormControl(''),
  });   
  constructor(
    private roomService: RoomService,
    private cinemaService: CinemaService
  ) { }   
  ngOnInit() {
    this.cinemaService.getAllCinemas().subscribe(data => {
      this.cinemas = data['content'];
      console.log(this.cinemas);
    });
    this.roomService.getAllTechnos().subscribe(data => {
      this.technos = data['content'];
      console.log(this.technos);
    });
  }    
  onAdd(): void {
    const room: Room = this.addRoomForm.value;
    this.roomService.createRoom(room).subscribe(data => {
      console.log(data);
    });
    console.log(room);
  }    
}

This is my code behind my Angular component.

HTML

<div class="container">
  <form class="room-add-form" [formGroup]="addRoomForm" enctype="application/x-www-form-urlencoded" (submit)="onAdd()">
    <mat-form-field class="room-add-full-width">
      <input matInput placeholder="Nom de la salle" formControlName="name">
    </mat-form-field>
    <mat-form-field class="room-add-full-width">
      <input matInput placeholder="Plan" formControlName="blueprint">
    </mat-form-field>
    <mat-form-field class="room-add-full-width">
      <input matInput type="number" placeholder="Nombre de place" formControlName="placelenght">
    </mat-form-field>
    <mat-form-field>
      <mat-select placeholder="Cinéma" formControlName="cinema">
        <mat-option *ngFor="let cinema of cinemas" [value]="cinema.id">
          {{cinema.name}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    <mat-form-field>
      <mat-select placeholder="Technologie" formControlName="techno">
        <mat-option *ngFor="let techno of technos" [value]="techno.id">
          {{techno.name}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    <button mat-button type="submit">Envoyer</button>
  </form>
</div>

I already tried to change the events during an update / delete in the table, this didn't work.

On Postman, the post request is working fine on my API.

Angular version : 7.3.1

EDIT

I forgot to add the error message

Cannot add or update a child row: a foreign key constraint fails (`cinego`.`salle`, CONSTRAINT `ref_salle_cinema` FOREIGN KEY (`idCinema`) REFERENCES `cinema` (`id`))
Answer 1

Is the table cinema populated first before inserting records in the salle table? I can see that cinema.idCinema is a reference key id for salle table so trying to validate it. Based from the error, a new entry must be present first in the cinema table before inserting a record in the salle table.

Answer 2

I found the solution to my problem, this side Angular, in my service that retrieves HTTP responses.

createRoom(item: Room): Observable<any> {
    return this.http.post<Room>(`${API_BASE_URL}/salle`, this.getFormUrlEncoded(item), {
      headers: new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded')
    });
  }

I added a function that manually encode the results of the Form into FormUrlEncode.

getFormUrlEncoded(toConvert) {
    const formBody = [];
    // tslint:disable-next-line: forin
    for (const property in toConvert) {
      const encodedKey = encodeURIComponent(property);
      const encodedValue = encodeURIComponent(toConvert[property]);
      formBody.push(encodedKey + '=' + encodedValue);
    }
    return formBody.join('&');
  }
READ ALSO
&ldquo;Writing configuration file failed&rdquo; in MySQL Server 8.0.15

“Writing configuration file failed” in MySQL Server 8.0.15

While set up the configuration in MySQL Server 80

32
Is there a standard connection dialog for mysql?

Is there a standard connection dialog for mysql?

I have written an windows form app in C# that gets distributed to various data partnersThe purpose of this app is to connect to one of their locally controlled databases, extract data according to SQL they provide and then to send it directly to our services...

33
Openproject installing to PostGre instead of MySQL

Openproject installing to PostGre instead of MySQL

Installing Openproject to a rented Ubuntu 1804 server

41