Skip to content

Instantly share code, notes, and snippets.

@LukeTowers
Last active February 7, 2017 22:30
Show Gist options
  • Save LukeTowers/8d8f5677b488e84abdc64cb0e7b8ccc3 to your computer and use it in GitHub Desktop.
Save LukeTowers/8d8f5677b488e84abdc64cb0e7b8ccc3 to your computer and use it in GitHub Desktop.
Query dump
/**
* Group messages by thread id pulling message and thread ids from the provided $queryScopes Query object
*
* @param QueryBuilder $query QueryBuilder object to apply the scope to
* @param QueryBuilder $queryScopes QueryBuilder object to use to get the message ids from
* @return QueryBuilder $query
*/
public function scopeGroupedByThread($query, $queryScopes = null)
{
$queryScopes = $queryScopes ?: $this->newQuery();
return $query->whereIn('id', array_values($queryScopes->lists('id', 'thread_id')));
}
public function scopeLatestReceivedGroupedByThread($query)
{
return $query
->groupedByThread((clone $query)
->received()
// Force getting via oldest first because the lsat item will be as the containing item by groupedByThread
->removeOrder('sent_at')
->oldest())
// Reorder the now grouped messages to get the desired order
->removeOrder('sent_at')
->newest();
}
public function scopeGroupedByThread($query)
{
$scopeIds = array_values($query->lists('id', 'thread_id'));
return $query->resetQuery()->whereIn('id', $scopeIds);
}
public function scopeLatestReceivedGroupedByThread($query)
{
return $query
->received()
// Force getting via oldest first because the lsat item will be as the containing item by groupedByThread
->removeOrder('sent_at')
->oldest()
->groupedByThread()
// Reorder the now grouped messages to get the desired order
->removeOrder('sent_at')
->newest();
}
public function scopeLatestReceivedGroupedByThread($query)
{
$groupedQuery = clone $query;
// Get the message ids to display flattened by groups, get by oldest first because the last item added to the thread_id key returned by lists
// will be the only one in that array element.
$groupedMessageIds = array_values($groupedQuery->received()->removeOrder('sent_at')->oldest()->lists('id', 'thread_id'));
// Get all messages in the previously selected array of ids, sort by newest this time
return $query->whereIn('id', $groupedMessageIds)->removeOrder('sent_at')->newest();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment