Created
May 31, 2018 19:08
-
-
Save Ellrion/02f55d9dcee4714acceff66de6bb776e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class BaseModel extends Model | |
{ | |
/** | |
* Находит последнюю запись для значений определенного поля. | |
* | |
* Т.е. с групировкой по указанному полю. | |
* | |
* @param Builder|QueryBuilder $query | |
* @param string $column | |
* @param array $values | |
* @param string $date | |
* @return Builder|QueryBuilder | |
*/ | |
public function scopeLastFor($query, $column, array $values = [], $date = 'created_at', $mergeWheres = true) | |
{ | |
if (!empty($values)) { | |
$query->whereIn($column, $values); | |
} | |
$sub_query = static::select("{$column} AS __{$column}")->selectRaw("MAX({$date}) as __{$date}")->groupBy($column); | |
if ($mergeWheres) { | |
$sub_query->mergeWheres($query->getQuery()->wheres, $query->getQuery()->getBindings()); | |
$query->getQuery()->mergeBindings($sub_query->getQuery()); | |
} | |
$query->join(new Expression("({$sub_query->toSql()}) as last_for_t"), function ($join) use ($column, $date) { | |
$join->on("last_for_t.__{$column}", '=', $column) | |
->on("last_for_t.__{$date}", '=', $date); | |
}); | |
return $query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment