Eloquent update() failing due to updated_at table ambiguity

给你一囗甜甜゛ 提交于 2019-12-08 16:29:16

问题


Ok, this question stems from a Laravel 4.1.23 install. I'm attempting to update multiple records using the Eloquent update() method on a query that includes a join:

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 is generating the correct SQL for the query content I'm providing above, but the full SQL statement generated is

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) 

This would work except that the automatically added updated_at field exists in both the child_school_years and school_years tables, so the addition of the field by Laravel triggers the Exception Integrity constraint violation: 1052 Column 'updated_at' in field list is ambiguous.

Any suggestions on how to domesticate the updated_at piece? I'd be happy to have the field updated, but I'll live without it if necessary should it be possible to eliminate it.


回答1:


There is no way to alter Eloquent behaviour, even adjusting UPDATED_AT column won't help, so you need to use either simple Query\Builder, like already suggested, or one of the methods below, that I find a bit better:

// 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(),
    )
  );


来源:https://stackoverflow.com/questions/25320335/eloquent-update-failing-due-to-updated-at-table-ambiguity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!