2016-09-04 57 views
2

如何将数据插入相关表?我有一个一对多的关系的两个相关表,下面是结构:Laravel 5将数据插入相关表?

版表:

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'); 
     }); 
    } 

期刊表:

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(); 
     }); 
    } 

版车型:

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

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

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

期刊模型:

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

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

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

版本表应该有许多期刊,就像一张拥有很多照片的专辑。那么,创建和保存方法如何呢?我也想和我得到这个错误“约束失败”,下面是代码:

控制器:

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

你如何在'store'方法中获得'edition_id'? – jaysingkar

+0

不知道如何,上面的方法存储不起作用 –

回答

3

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'); 
    } 

是应该在打开一个创建表单按钮代码假设,edition_id在输入变量中,以下是如何添加属于特定editionjournal

$edition_id = $request->get('edition'); //replace this with your way of retrieving edition_id 
$journal = Edition::findOrFail($edition_id)->journal()->create($input);