由于updated_at表歧义,Eloquent update()失败



好吧,这个问题源于安装Laravel 4.1.23。我试图在包含连接的查询上使用Eloquent update()方法更新多条记录:

ChildSchoolYear::whereNull('exit_date')->
join('school_years', 'child_school_years.school_year_id','=','school_years.id')->
update(array('child_school_years.exit_date'=>'`school_years`.`end_date`',
'child_school_years.editor_id'=>$userId))

Laravel正在为我上面提供的查询内容生成正确的SQL,但生成的完整SQL语句是

update `child_school_years` 
inner join `school_years` on `child_school_years`.`school_year_id` = `school_years`.`id` 
set `child_school_years`.`exit_date` = `school_years`.`end_date`,
`child_school_years`.`editor_id` = 2, 
`updated_at` = 2014-08-15 02:00:33 where `exit_date` is null) 

除了自动添加的updated_at字段同时存在于child_school_years和school_years表中,所以Laravel添加该字段会触发异常Integrity constraint violation: 1052 Column 'updated_at' in field list is ambiguous

关于如何驯化updated_at片段有什么建议吗?我很高兴有字段更新,但如果有必要,我将没有它,如果有可能消除它。

没有办法改变雄辩的行为,即使调整UPDATED_AT列也无济于事,所以你需要使用简单的QueryBuilder,就像已经建议的那样,或者下面的方法之一,我发现更好一点:

// easiest way
ChildSchoolYear::whereNull('exit_date')
  ->join('school_years', 'child_school_years.school_year_id','=','school_years.id')
  ->getQuery()  // get underlying base QueryBuilder
  ->update(
    array(
      'child_school_years.exit_date'  => '`school_years`.`end_date`',
      'child_school_years.editor_id'  => $userId,
      'child_school_years.updated_at' => CarbonCarbon::now(),
    )
  );
// also would work, temporary turn off auto timestamps
with($model = new ChildSchoolYear)->timestamps = false;
// above is the same as:
// $model = new ChildSchoolYear;
// $model->timestamps = false;
$model->whereNull('exit_date')
  ->join('school_years', 'child_school_years.school_year_id','=','school_years.id')
  ->update(
    array(
      'child_school_years.exit_date'  => '`school_years`.`end_date`',
      'child_school_years.editor_id'  => $userId,
      'child_school_years.updated_at' => CarbonCarbon::now(),
    )
  );

最新更新