【问题标题】:Eager Loading confusion. How to reduce queries渴望加载混乱。如何减少查询
【发布时间】: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。

【问题讨论】:

    标签: eloquent eager-loading


    【解决方案1】:

    预加载应该是这样工作的。

    使用联接合并所有查询仅适用于一对一关系。如果您加入一对多或多对多的关系,您将获得巨大的结果。

    即使在像您这样的情况下,多个简单查询也可能会更快(或者至少不会 慢)比一个复杂的查询。您还必须为所有列添加别名以处理重复的列名(country.codelanguage.code 等)。

    【讨论】:

      猜你喜欢
      • 2014-12-15
      • 2011-07-20
      • 2014-03-13
      • 2013-05-06
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多