为什么模型方法中的 ->latest 方法读取相关 table 中的所有行?
Why ->latest method in model method read all rows from related table?
在 laravel 9 中,我得到了相关 CurrencyHistory 中的最后一个值 table
$currencies = Currency
::getByActive(true)
->withCount('currencyHistories')
->with('latestCurrencyHistory')
->orderBy('ordering', 'asc')
->get();
在模型 app/Models/Currency.php 中我有:
public function latestCurrencyHistory()
{
return $this->hasOne('App\Models\CurrencyHistory')->latest();
}
但是检查生成的 sql 我看到像这样的行:
SELECT *
FROM `currency_histories`
WHERE `currency_histories`.`currency_id` in (8, 13, 16, 19, 27, 30)
ORDER BY `created_at` desc
我想这段代码是由 latestCurrencyHistory 方法引发的,不知道可以
我这里设置了一些limit 1的条件,因为结果数据太大了。
谢谢!
查询正确。当您急于使用 with
方法加载 集合 货币的关系时,您为集合中的所有 Currency
模型加载 currency_histories
。
如果转储结果,您将拥有 ID 为:8、13、16、19、27、30 和每个 ID 一个 latestCurrencyHistory
(如果存在)的货币。
在 laravel 9 中,我得到了相关 CurrencyHistory 中的最后一个值 table
$currencies = Currency
::getByActive(true)
->withCount('currencyHistories')
->with('latestCurrencyHistory')
->orderBy('ordering', 'asc')
->get();
在模型 app/Models/Currency.php 中我有:
public function latestCurrencyHistory()
{
return $this->hasOne('App\Models\CurrencyHistory')->latest();
}
但是检查生成的 sql 我看到像这样的行:
SELECT *
FROM `currency_histories`
WHERE `currency_histories`.`currency_id` in (8, 13, 16, 19, 27, 30)
ORDER BY `created_at` desc
我想这段代码是由 latestCurrencyHistory 方法引发的,不知道可以 我这里设置了一些limit 1的条件,因为结果数据太大了。
谢谢!
查询正确。当您急于使用 with
方法加载 集合 货币的关系时,您为集合中的所有 Currency
模型加载 currency_histories
。
如果转储结果,您将拥有 ID 为:8、13、16、19、27、30 和每个 ID 一个 latestCurrencyHistory
(如果存在)的货币。