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

时间:2014-08-15 02:14:02

标签: php laravel-4 eloquent

好的,这个问题源于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) 

除了child_school_years和school_years表中都存在自动添加的updated_at字段之外,这将有效,因此Laravel添加字段会触发异常Integrity constraint violation: 1052 Column 'updated_at' in field list is ambiguous

有关如何驯化updated_at作品的任何建议?我很乐意让这个领域得到更新,但是如果有必要的话,我会在没有它的情况下生活。如果可以消除它。

1 个答案:

答案 0 :(得分:12)

无法改变Eloquent行为,即使调整UPDATED_AT列也没有帮助,因此您需要使用简单的Query\Builder,如已建议的那样,或者下面的方法之一,我觉得好一点:

// easiest way
ChildSchoolYear::whereNull('exit_date')
  ->join('school_years', 'child_school_years.school_year_id','=','school_years.id')
  ->getQuery()  // get underlying base Query\Builder
  ->update(
    array(
      'child_school_years.exit_date'  => '`school_years`.`end_date`',
      'child_school_years.editor_id'  => $userId,
      'child_school_years.updated_at' => Carbon\Carbon::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' => Carbon\Carbon::now(),
    )
  );