【发布时间】:2018-03-02 15:44:40
【问题描述】:
我可能错过了急切加载的要点,但我想澄清一下。
当我运行以下查询时:
Capsule::connection()->enableQueryLog();
$result = Application::with([
'country',
'language',
])
->where('application.id', $applicationId)
->where('application.merchant_id', $merchantId)
->firstOrFail();
var_dump(Capsule::getQueryLog());
exit;
我得到了输出:
string(100) "select * from `application` where `application`.`id` = ? and `application`.`merchant_id` = ? limit 1"
string(53) "select * from `country` where `country`.`code` in (?)"
string(55) "select * from `language` where `language`.`code` in (?)"
我期望生成的 sql 是一个带有几个连接的查询。
我意识到这不是一个 n+1 的问题。就性能而言,也许在这里执行三个查询而不是一个实际上并不是什么大问题。但我想知道如何将其减少为一个查询。我尝试使用join,但仍然导致三个查询:
string(316) "select * from `application` inner join `country` on `country`.`code` = `application`.`country_id` inner join `currency` on `currency`.`code` = `application`.`currency_id` inner join `language` on `language`.`code` = `application`.`language_id` where `application`.`id` = ? and `application`.`merchant_id` = ? limit 1"
string(53) "select * from `country` where `country`.`code` in (?)"
string(55) "select * from `language` where `language`.`code` in (?)"
所以我的问题是……
如何将其简化为单个查询,并能够使用 Eloquent 的关系方面来获取应用程序的国家和语言数据?
如果这对您的答案有任何影响,我不会使用 Laravel 框架。我正在使用 Slim 3。
【问题讨论】: