Методи `latestOfMany()` та `oldestOfMany()` у Laravel спрощують отримання найсвіжіших або найстаріших пов'язаних моделей через Eloquent-відносини. Вони перетворюють складні запити на прості та зрозумілі асоціації.
Ця функція особливо корисна для застосунків, які відстежують історію, показують останні дії або зберігають записи про перші події.
class User extends Model
{
public function latestLogin(): HasOne
{
return $this->hasOne(Login::class)->latestOfMany();
}
public function firstPurchase(): HasOne
{
return $this->hasOne(Purchase::class)->oldestOfMany();
}
}
Ось практичний приклад відстеження взаємодій із клієнтами:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
class Customer extends Model
{
public function mostRecentInteraction(): HasOne
{
return $this->hasOne(Interaction::class)->latestOfMany();
}
public function mostValuedPurchase(): HasOne
{
return $this->hasOne(Purchase::class)->ofMany('total_amount', 'max');
}
public function firstSubscription(): HasOne
{
return $this->hasOne(Subscription::class)->oldestOfMany('started_at');
}
public function currentMembership(): HasOne
{
return $this->hasOne(Membership::class)->latestOfMany()->where('status', 'active');
}
}
Ці відносини можна безперешкодно використовувати у запитах:
// Отримання клієнтів з відповідними даними про відносини
$customers = Customer::with([
'mostRecentInteraction',
'mostValuedPurchase',
'firstSubscription',
'currentMembership'
])->get();
// Природний доступ до даних
foreach ($customers as $customer) {
dump("Остання взаємодія: " . $customer->mostRecentInteraction->created_at);
dump("Найбільша покупка: $" . $customer->mostValuedPurchase->total_amount);
}
Методи `latestOfMany` і `oldestOfMany` перетворюють складні вимоги до сортування та фільтрації на чисті, читабельні відносини.