In laravel 9 I got last value in related CurrencyHistory table
$currencies = Currency
::getByActive(true)
->withCount('currencyHistories')
->with('latestCurrencyHistory')
->orderBy('ordering', 'asc')
->get();
In model app/Models/Currency.php I have :
public function latestCurrencyHistory()
{
return $this->hasOne('App\Models\CurrencyHistory')->latest();
}
But checking generated sql I see lines like :
SELECT *
FROM `currency_histories`
WHERE `currency_histories`.`currency_id` in (8, 13, 16, 19, 27, 30)
ORDER BY `created_at` desc
I suppose this code is raised by latestCurrencyHistory method and wonder can I set some limit 1 condition here, as resulting data are too big.
Thanks!
CodePudding user response:
Query is correct. As you eager load your relation for the collection of currencies using with
method, you load currency_histories
for all of your Currency
models in collection.
If you dump the result, you will have currencies with IDs: 8, 13, 16, 19, 27, 30 and one latestCurrencyHistory
(if present) for each.