0

我有以下具有可填充属性的模型:

class Job extends Model {

    protected $fillable = [
      'job_type_id',
      'recruiter_id',
      'start_at',
      'end_at',
      'job_title',
      'job_ref',
      'job_desc'

    ];

    // other stuff
 }

我有一个表格来更新工作,其中包括一些多选下拉列表,如下所示:

<form class="js-job-posting" enctype="multipart/form-data" accept-charset="UTF-8" action="http://localhost:8000/jobs/2" method="POST">
   <input type="hidden" value="PATCH" name="_method">
   <input type="hidden" value="iElj170OKBLg9THP7iETwsn34iuVhdpBX3hF98UA" name="_token">
   <div class="form-group ">
       <label for="job_title">Job title</label>
       <input id="job_title" class="form-control" type="text" name="job_title">
   </div>

   <div class="form-group ">
      <label for="industry_list">Industry</label>
      <select id="industry_list" class="form-control name="industry_list[]" multiple="" >
         <option value="1">Accounting</option>
         <option value="37">Administration</option>
          ...
       </select>
    </div>
 </form>

在我的控制器中,我有以下方法来更新作业,但出现错误:

ErrorException in helpers.php line 671: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

似乎 usingAuth::user()->recruiter->jobs()->update($request->except('job_type_id'));会导致此错误,因为请求对象包含行业列表的数组。但是为什么这很重要,因为我已经在 J​​ob 类上定义了质量可填充属性?

public function update(JobRequest $request, $id)
{
   $job = Job::findOrFail($id);

   Auth::user()->recruiter->jobs()->update($request->except('job_type_id'));

   $job->industries()->sync($request->input('industry_list'));

   flash()->success('Job details have been updated');

   return redirect('/job/' . $id . '/edit');
}

奇怪的是,当我按如下方式排除行业列表:Auth::user()->recruiter->jobs()->update($request->except('job_type_id', industry_list'));然后进行更新时,我收到以下 sql 错误:

 SQLSTATE[42S22]: Column not found: 1054 Unknown column '_method' in 'field list' (SQL: update `jobs` set `_method` = PATCH, `_token` = iElj170OKBLg9THP7iETwsn34iuVhdpBX3hF98UA,...

为什么生成的 SQL 包含更新表单中的每个字段,包括 _method 和 _token?

与忽略可填充字段的查询构建器有关吗?

4

1 回答 1

0

如果您只有一个字段要更新,请使用:

->update($request->only('job_title'));

否则,您应该排除所有其他字段,如下所示:

->update($request->except(['job_type_id', 'industry_list', '_method', '_token']));

$fillable在对关系进行更新时不查看属性。

于 2016-09-06T20:52:53.540 回答