【问题标题】:Eloquent update() failing due to updated_at table ambiguity由于 updated_at 表的歧义,雄辩的 update() 失败
【发布时间】:2014-08-15 02:14:01
【问题描述】:

好的,这个问题源于 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 片段有什么建议吗?我很乐意更新该字段,但如果有必要,如果可以消除它,我会不使用它。

【问题讨论】:

标签: php laravel-4 eloquent


【解决方案1】:

没有办法改变 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(),
    )
  );

【讨论】:

  • getQuery() 语句来自哪里?我在任何地方都找不到它的定义。这两种方法看起来都有希望,但如果我能获得更多信息,我更喜欢使用 getQuery()。
  • 其实我也对 with() 函数的定义位置感兴趣。我似乎在 Laravel.com 在线文档中都找不到。
  • 查看源码,这是学习框架的最佳途径。它也有很好的记录。 getQuery 这里是 Eloquent\Builders 方法,with 只是在 Illuminate\Support\helpers.php 中定义的一个小助手 - 助手文档中的最后一个:laravel.com/docs/helpers
  • 感谢您的参考。我想我已经被 PHP 文档宠坏了,它通常解释了每个函数的基础知识 - 涉足 Laravel 源代码可以让你弄清楚事情,但到目前为止我很少发现它实际上可以直接解释。我还发现有时在线浏览源代码非常困难。尽管如此,该建议仍然有用。谢谢。
  • 不,不是在线资源。获取您的应用程序中的代码。如果您想了解事物的工作原理,在线 API 文档几乎没有用处。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 2020-06-23
  • 1970-01-01
  • 2015-03-31
  • 2015-12-05
  • 1970-01-01
相关资源
最近更新 更多