Laravel 5.1 表单模型绑定一对多关系


Laravel 5.1 form model binding a one to many relationship

使用数组时是否可以形成模型绑定一对多关系?

在下面的示例中,我在工作问题表之间有一对多的关系。

一个作业可以有很多问题,也可以没有与之关联的问题。在我的刀片模板中,我想知道是否可以绑定此关系因为我已经能够在工作类getIndustryListAttribute()上使用简单的方法对工作行业关系做到这一点。我尝试使用getQuestionListAttribute()方法,但它不起作用?

表:

 jobs
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`job_title` VARCHAR(100) NOT NULL,
questions
`job_id` INT(10) UNSIGNED NOT NULL,
`question_id` INT(10) UNSIGNED NOT NULL,
`question_text` VARCHAR(150) NOT NULL,
`expected_answer` TINYINT(1) NOT NULL,
    PRIMARY KEY (`job_id`, `question_id`),

模型:

class Job extends Model {
    public function questions()
    {
        return $this->hasMany('App'Question');
    }
    public function industries()
    {
        return $this->belongsToMany('App'Industry', 'job_industry');
    }
    public function getIndustryListAttribute()
    {
        return $this->industries->lists('id')->all();
    }
    public function getQuestionListAttribute()
    {
        return $this->questions->lists('question_text', 'question_id')->all();
    }
}
class Question extends Model {
    public function job()
    {
        return $this->belongsTo('App'Job');
    }
}

形式:

   @for ($i = 0; $i < 5; $i++)
       <div class="form-group >
          {!! Form::label("question_list.{$i}.question_text", 'Question', ['class' => '']) !!}
          {!! Form::text("question_list[{$i}][question_text]", null, ['maxlength' => '150', 'class' => 'form-control']) !!}
       </div>
       <div class="form-group">
          {!! Form::label("question_list.{$i}.expected_answer", 'Expected answer', ['class' => '']) !!}
          {!! Form::select("question_list[{$i}][expected_answer]", ['' => 'Please Select', 'true' => 'Yes', 'false' => 'No'], null, ['class' => 'form-control']) !!}
      </div>
    @endfor
     <div class="form-group">
         {!! Form::label('industry_list', 'Industry', ['class' => '']) !!}
         {!! Form::select('industry_list[]', $industries, null, ['id' => 'industry_list', 'class' => 'form-control', 'multiple']) !!}
     </div>

注意:question_id只是数组索引值。

可以使用Form Model Accessors绑定一对多关系

class Job extends Model 
{
    use 'Collective'Html'Eloquent'FormAccessible;
    public function formQuestionAttribute($value)
    {
        // This will return array, You want to implode it if you expect string.
        return $this->questions;
    }
}

在刀片式服务器文件中:

{!! Form::text('questions') !!}

参见 LaravelCollective 了解更多信息。