update() sets updated_at but fails due to join
If you're building an Eloquent query from a model that has timestamps and you attempt to join table that also contains timestamps (ie. updated_at) and then call update() on the builder, then it will fail since updated_at is now ambigous. Since there's no way to change the updated_at field definition in an update() call, it's impossible to use update() when joining and using timestamps.
Example:
private function getPackingScannerQuery($since) {
return ChipScan::where('is_processed', 0)
->where(ChipScan::table().'.antenna_id', 1)
->where(ChipScan::table().'.created_at', '>=', $since)
->join(Chip::table().' AS c', 'c.id', '=', ChipScan::table().'.chip_id')
->join(ChipData::table().' AS cd', 'cd.id', '=', 'c.chip_data_id');
}
ChipScan::table() returns the table name of the model. Laravel doesn't seem to have a shorthand for this. Both ChipScan, Chip and ChipData are timestamped with created_at and updated_at.
Then method is called:
$scanned = $this->getPackingScannerQuery(...);
$scanned->update(['is_processed' => 1]); // This will fail: column name "updated_at" is ambigous
My current workaround is to select all ids from ChipScan, but even that cannot be done since lists() will strip table aliases, so I also employ a workaround for that (there's apparently a PR for that issue as well). Anyhow, to work around it I have to do all this:
// Laravel bug: Normally, we'd run a update(...) on the query, but Laravel adds updated_at which is ambigous because we're joining
// So collect all ChipScan.id and manually update fields
// Laravel bug: lists() will strip table name, so since it's a join, 'id' too is ambigous. Wtf, Taylor?!
$scan_ids = $scanned->select(ChipScan::table().'.id AS _id')->lists('_id');
ChipScan::whereIn('id', $scan_ids ?: [null])->update(['is_processed' => 1]);
I suspect this is fixed now.
I have this issue. Why was it closed? Is there a solution?
This has been reconfirmed as a bug here: https://github.com/laravel/framework/issues/11815
I still have this issue, Not fixed yet.