Laravel 5将数据插入相关表格?

时间:2016-09-04 03:54:30

标签: laravel 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');
    }
}

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

控制器:

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

应该在以下位置打开创建表单的按钮代码:

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

1 个答案:

答案 0 :(得分:3)

假设edition_id位于输入变量中,此处为您添加属于journal的{​​{1}}的方式:

edition