Laravel wprowadza nowe metody usprawniające zapytania o negatywne relacje, ułatwiając znajdowanie rekordów, które nie mają określonych relacji, przy jednoczesnym zachowaniu czystego, czytelnego kodu.
Nowe metody whereDoesntHaveRelation zapewniają zwięzły sposób wyszukiwania rekordów bez określonych relacji:
User::whereDoesntHaveRelation(
'posts',
'published_at',
'>',
now()->subWeek()
)->get();
User::whereMorphDoesntHaveRelation(
'activities',
[Comment::class, Review::class],
'is_featured',
true
)->get();
Metody te okazują się szczególnie cenne w systemach zarządzania treścią:
class ContentManager
{
public function findDormantAuthors()
{
return User::whereDoesntHaveRelation(
'articles',
'published_at',
'>',
now()->subDays(60)
)->get();
}
public function getUnmoderatedContent()
{
return Article::whereDoesntHaveRelation(
'moderations',
'reviewed_at',
'!=',
null
)->get();
}
public function getUnpopularContent()
{
return Article::whereMorphDoesntHaveRelation(
'reactions',
[Like::class, Share::class, Bookmark::class],
'created_at',
'>',
now()->subMonth()
)->get();
}
public function archiveStaleContent()
{
return Article::query()
->whereDoesntHaveRelation('comments', 'id', '!=', null)
->whereDoesntHaveRelation('views', 'id', '!=', null)
->whereDoesntHaveRelation(
'updates',
'created_at',
'>',
now()->subMonths(6)
)
->update(['status' => 'archived']);
}
}
Te nowe metody eliminują potrzebę stosowania złożonych zamknięć whereDoesntHave, dzięki czemu zapytania o negatywne relacje są bardziej intuicyjne i łatwiejsze w utrzymaniu, jednocześnie poprawiając czytelność kodu.