简体   繁体   English

Eager Loading 是否区分大小写?

[英]Is Eager Loading case-sensitive?

Taking in consideration the documentation https://laravel.com/docs/5.0/eloquent#eager-loading lets have the following example:考虑到文档https://laravel.com/docs/5.0/eloquent#eager-loading让我们有以下示例:

$clients = Clients::with('Addresses')->get();

We can now loop addresses like:我们现在可以像这样循环addresses

foreach ($clients->Addresses ..) 

foreach ($clients->addresses ..) 

If we use the first approach (with case-sensitive) does that mean that the Eager Loading results will be ignored and another query will be done or not?如果我们使用第一种方法(区分大小写),这是否意味着将忽略 Eager Loading 结果并执行另一个查询?

As you know, If we do something like:如您所知,如果我们执行以下操作:

$clients = Clients::get();

We are still able to loop through the addresses but another query will be taking place.我们仍然可以遍历这些地址,但将进行另一个查询。

foreach ($clients->Addresses ..)

From some quick tests, it seems that while Eager Loaded is in fact case-insensitive, it is only so when using the same case while loading and while accessing.从一些快速测试来看,虽然 Eager Loaded 实际上是不区分大小写的,但只有在加载和访问时使用相同的大小写时才如此。 For your example:对于您的示例:

$clients = Client::with(['addresses' => function ($q) {
  $q->limit(2);
}])->get();

// Good
foreach ($clients as $client){
  foreach ($client->addresses as $address) {
    // Should loop twice and output 2 Addresses
  }
}

// Bad
foreach ($clients as $client){
  foreach ($client->Addresses as $address) {
    // Will loop X times for each associated `address`
  }
}

The use of DB::enableQueryLog() and DB::getQueryLog() can assist with debugging.使用DB::enableQueryLog()DB::getQueryLog()可以帮助调试。 If you're eager loading, you should see a row:如果你急于加载,你应该看到一行:

"query" => "select * from `addresses` where `addresses`.`client_id` in (...) limit 1

If an additional query is being run while iterating, you'll see a query for each Client:如果在迭代时正在运行其他查询,您将看到每个客户端的查询:

"query" => "select * from `addresses` where `addresses`.`client_id` = ? and `addresses`.`client_id` is not null",

There are a multitude of other methods to test this, but the long and short of it is that accessing $client->addresses and $client->Addresses does in fact produce different outcomes, even if they seem similar.有许多其他方法可以对此进行测试,但总而言之,访问$client->addresses$client->Addresses实际上会产生不同的结果,即使它们看起来相似。 Use the same case for loading that you use while accessing and you'll be good.使用与访问时相同的情况进行加载,您会很好。 Note that since relationships are functions, using the correct case for PHP functions ( studlyCaps aka pascalCase ) should be your go-to approach.请注意,由于关系是函数,因此对 PHP 函数( studlyCaps aka pascalCase )使用正确的大小写应该是您的首选方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM