【问题标题】:Laravel 5.1 form model binding a one to many relationshipLaravel 5.1 表单模型绑定一对多关系
【发布时间】:2016-06-11 01:40:44
【问题描述】:

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

在下面的示例中,jobsquestions 表之间存在一对多关系。

一项工作可以有很多或没有与之相关的问题。在我的刀片模板中,我想知道是否可以绑定这种关系 因为我已经能够在工作类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 只是数组索引值。

【问题讨论】:

    标签: php laravel-5.1 model-binding laravel-blade laravel-form


    【解决方案1】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 2014-12-31
      • 2016-05-25
      • 2016-03-02
      • 2016-04-12
      • 2013-12-09
      • 2014-12-06
      相关资源
      最近更新 更多