2016-09-04 3 views
2

Wie fügt man Daten in verwandte Tabellen ein? Ich habe zwei verknüpften Tabellen mit einer Eins-zu-viele-Beziehung, unten ist die Struktur:Laravel 5 Daten in verwandte Tabellen einfügen?

Ausgabe Tisch:

public function up() 
    { 
     Schema::create('edition', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('title')->unique(); 
      $table->text('cover')->nullable(); 
      $table->timestamps(); 
     }); 

     //Set FK di kolom id_edition di table Journal 
     Schema::table('journal', function(Blueprint $table) { 
      $table->foreign('id_edition')->references('id')->on('edition')->onDelete('cascade')->onUpdate('cascade'); 
     }); 
    } 

Journal Tabelle:

public function up() 
    { 
     Schema::create('journal', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('title', 200); 
      $table->string('author'); 
      $table->text('abstract'); 
      $table->text('file'); 
      $table->integer('id_edition')->unsigned(); 
      $table->timestamps(); 
     }); 
    } 

Ausgabe Modell:

class Edition extends Model 
{ 
    protected $table = 'edition'; 

    protected $fillable = [ 
     'title', 
     'cover', 
    ]; 

    public function journal() 
    { 
     return $this->hasMany('App\Journal', 'id_edition'); 
    } 
} 

Journal-Modell:

class Journal extends Model 
{ 
    protected $table = 'journal'; 

    protected $fillable = [ 
     'title', 
     'author', 
     'abstract', 
     'file', 
    ]; 

    public function edition() 
    { 
     return $this->belongsTo('App\Edition', 'id_edition'); 
    } 
} 

Die Editionstabelle soll viele Zeitschriften enthalten, wie ein Album, das viele Fotos hat. Wie also würden die create und die save Methode aussehen? Ich habe versucht, und ich bekomme diese Fehlermeldung "Constraint versagt", unten sind die Codes:

Controller:

public function create() { 
     return view('journal/create'); 
    } 

    public function store(JournalRequest $request, Edition $edition) { 
     $input = $request->all(); 

     //Input PDF 
     if ($request->hasFile('file')) { 
      $input['file'] = $this->uploadPDF($request); 
     } 

     //Insert data journal 
     $journal = Journal::create($input); 

     return redirect('journal'); 
    } 

Die Schaltfläche Code, der eine erstellen Form in öffnen soll:

<div class="tombol-nav"> 
<a href="../journal/create?edition={{$edition->id}}" class="btn btn-primary">Add new Journal to this edition</a> 
</div> 
+0

Wie bekommen Sie 'edition_id' in der' store' Methode? – jaysingkar

+0

keine Ahnung wie, der Methodenspeicher oben funktioniert nicht –

Antwort

3

Angenommen, edition_id ist in der Eingangsvariablen, hier ist, wie Sie die journal gehören zu spezifischen edition:

hinzufügen können