2017-03-15 11 views
1

Willkommen! Ich habe zwei Tabellen in den Datenbankanmerkungen und in den Piloten und ich möchte Anmerkungen anzeigen, die Piloten gehören. Ich fügte hinzu, Fremdschlüssel, um Notizen Tabelle, aber ich habe ein solches Problem, wenn ich versuche, neue Notiz zu erstellen:laravel - Abfrage mit Fremdschlüssel

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`app`.`notes`, CONSTRAINT `notes_pilot_id_foreign` FOREIGN KEY (`pilot_id`) REFERENCES `pilots` (`id`)) 

Hinweis Modell:

class Note extends Model 
    { 
     protected $table = 'notes'; 
     /** 
     * The attributes that are mass assignable. 
     * 
     * @var array 
     */ 
     protected $fillable = [ 
      'data', 'zadanie', 'uwagi', 'pilot_id', 
     ]; 

     public function pilot() { 
      return $this->belongsTo(Pilot::class); 
     } 
    } 

Pilot Modell:

class Pilot extends Model 
{ 
    protected $table = 'pilots'; 
    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'name', 'phone', 'email', 
    ]; 

    public function note() { 
     return $this->hasMany(Note::class); 
    } 
} 

Hinweis Controller speichern methode:

public function store(Request $request) 

{ 

    $this->validate($request, [ 

     'data' => 'required', 

     'zadanie' => 'required', 

     'uwagi' => 'required', 

    ]); 


    $note = new Note (array(
     'data' => $request->get('data'), 
     'zadanie' => $request->get('zadanie'), 
     'uwagi' => $request->get('uwagi'), 

    )); 
    $note->save(); 
    $note->pilot()->sync($request->get('pilots')); 

    return redirect()->route('uwagi.index') 

        ->with('success','Uwagi dodane poprawnie'); 

} 
+0

Sie sollten Fremdschlüssel in Ihrer Migration oder Ihre Datenbanktabellen überprüfen. –

Antwort

0

Versuchen dies Rückgabe $ this-> hasMany ('App \ Note'); Und Versuchen Sie diese Rückgabe $ This-> AngleTo ('App \ Pilot');

0

Problem gelöst. Ich habe den Fremdschlüssel in der öffentlichen Funktion bei der Migration einfach nicht gelöscht.