在 Laravel function 中防止重复调用 SQL:使用 once helper
有时,在 Laravel function 中,我们会想要避免在重复使用的地方多次调用 SQL。 <https://laravel news.com/once helper <https://laravel.com/docs/11.x/helpers method once 这时可以使用的 helper 就是 once
GGAMI
有时,在 Laravel function 中,我们会想要避免在重复使用的地方多次调用 SQL。
https://laravel-news.com/once-helper https://laravel.com/docs/11.x/helpers#method-once
这时可以使用的 helper 就是 once 辅助函数。 比想象中好用。
public static function getExchangeNames(Exchange $exchange): array
{
return once(function () use ($exchange) {
return self::where('exchange', $exchange)
->get()
->pluck('name')
->toArray();
});
}如果使用不同的 $exchange 值调用 function,就会相应地发送新的 SQL 请求。
比想象中实用。