framework icon indicating copy to clipboard operation
framework copied to clipboard

update() sets updated_at but fails due to join

Open scarlac opened this issue 12 years ago • 4 comments

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]);

scarlac avatar Aug 13 '14 10:08 scarlac

I suspect this is fixed now.

GrahamCampbell avatar Dec 27 '14 14:12 GrahamCampbell

I have this issue. Why was it closed? Is there a solution?

kdoonboli avatar Apr 23 '16 00:04 kdoonboli

This has been reconfirmed as a bug here: https://github.com/laravel/framework/issues/11815

samrap avatar May 11 '16 01:05 samrap

I still have this issue, Not fixed yet.

Amina24 avatar Mar 22 '17 09:03 Amina24