Comments (7)
Good tip!
Remembered I had to solve this in the past too. For those interested:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
trait GroupedLastScope
{
/**
* Get the latest entry for each group.
*
* Each group is composed of one or more columns that make a unique combination to return the
* last entry for.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array|null $fields A list of fields that's considered as a unique entry by the query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeLastPerGroup(Builder $query, ?array $fields = null) : Builder
{
return $query->whereIn('id', function (QueryBuilder $query) use ($fields) {
return $query->from(static::getTable())
->selectRaw('max(`id`)')
->groupBy($fields ?? static::$groupedLastScopeFields);
});
}
}
from blog-contest-may-mayhem.
My memory's a little foggy trying to remember this use case ๐ Given the example in the opening post where a users has a lot of messages and we want the last message per user:
$latest = Message::query()
->lastPerGroup(['user_id'])
->get()
Which will (should) return a list of recent messages, one per user.
If you want to be sure you're getting the latest by date instead of by auto-incremented ID, I suppose you can change max(
id)
to max(
created_at)
in the scope.
from blog-contest-may-mayhem.
What if the table doesn't have a id
column?
from blog-contest-may-mayhem.
Good tip!
Remembered I had to solve this in the past too. For those interested:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; trait GroupedLastScope { /** * Get the latest entry for each group. * * Each group is composed of one or more columns that make a unique combination to return the * last entry for. * * @param \Illuminate\Database\Eloquent\Builder $query * @param array|null $fields A list of fields that's considered as a unique entry by the query. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeLastPerGroup(Builder $query, ?array $fields = null) : Builder { return $query->whereIn('id', function (QueryBuilder $query) use ($fields) { return $query->from(static::getTable()) ->selectRaw('max(`id`)') ->groupBy($fields ?? static::$groupedLastScopeFields); }); } }
Usage example?
from blog-contest-may-mayhem.
@sebastiaanluca has some exemple?
from blog-contest-may-mayhem.
Good tip!
Remembered I had to solve this in the past too. For those interested:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; trait GroupedLastScope { /** * Get the latest entry for each group. * * Each group is composed of one or more columns that make a unique combination to return the * last entry for. * * @param \Illuminate\Database\Eloquent\Builder $query * @param array|null $fields A list of fields that's considered as a unique entry by the query. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeLastPerGroup(Builder $query, ?array $fields = null) : Builder { return $query->whereIn('id', function (QueryBuilder $query) use ($fields) { return $query->from(static::getTable()) ->selectRaw('max(`id`)') ->groupBy($fields ?? static::$groupedLastScopeFields); }); } }
Where should I put this code?
I have tried to make this work and I have not been able to achieve it.
from blog-contest-may-mayhem.
Good tip!
Remembered I had to solve this in the past too. For those interested:<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; trait GroupedLastScope { /** * Get the latest entry for each group. * * Each group is composed of one or more columns that make a unique combination to return the * last entry for. * * @param \Illuminate\Database\Eloquent\Builder $query * @param array|null $fields A list of fields that's considered as a unique entry by the query. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeLastPerGroup(Builder $query, ?array $fields = null) : Builder { return $query->whereIn('id', function (QueryBuilder $query) use ($fields) { return $query->from(static::getTable()) ->selectRaw('max(`id`)') ->groupBy($fields ?? static::$groupedLastScopeFields); }); } }
Where should I put this code?
I have tried to make this work and I have not been able to achieve it.
It's a trait, in a different php file then "Use GroupedLastScope" on the top of your model
from blog-contest-may-mayhem.
Related Issues (20)
- Logging model changes and 11 other ways to improve your Laravel projects HOT 1
- Avoid Race condition using lockForUpdate function and MySQL transactions.
- Realtime Job Management With Laravel and Vue HOT 1
- File upload with Laravel and VueJS HOT 6
- Cloaking field names to add more layer of security in your form.
- Masking IDs in URLs using hashids in Laravel HOT 2
- Ordering with JSON in Laravel
- Encrypting Your Model Attributes
- Encrypting your Model Attributes HOT 4
- Laravel Innovations: Making your own webhook mechanism through notifications HOT 2
- Introduction to Laravelโฆ for an Eight-Year-Old
- The Magical Use of Macroables in Laravel
- Dynamic Eloquent Relation Byย Macro
- Getting Started With LaravelโโโThe Lift Off
- The Good, the Bad and the Ugly of seeding data in production HOT 5
- Solving common public key problems in Laravel Forge (a.k.a. Forgetastic pubkeys and where to find them)
- Differentiate Laravel collections methods
- Laravel Continuous Integration & Delivery with Bitbucket Pipelines
- Extending an Open Source Tool with Laravel Spark
- Domain Driven Design in Laravel
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog-contest-may-mayhem.