Skip to content

Commit e8d1aa6

Browse files
committed
Merge pull request #466 from jpfuentes2/anther-faster_relationships
Faster relationships
2 parents 6309d9e + d3da94a commit e8d1aa6

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

lib/Relationship.php

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -184,24 +184,36 @@ protected function query_and_attach_related_models_eagerly(Table $table, $models
184184
$model_values_key = $inflector->variablize($model_values_key);
185185
$query_key = $inflector->variablize($query_key);
186186

187+
$all_related_with_value = null;
187188
foreach ($models as $model)
188189
{
190+
if(!isset($all_related_with_value))
191+
{
192+
$all_related_with_value = array();
193+
foreach ($related_models as $related)
194+
{
195+
$all_related_with_value[$related->$query_key][] = $related;
196+
}
197+
}
189198
$matches = 0;
190199
$key_to_match = $model->$model_values_key;
191200

192-
foreach ($related_models as $related)
201+
if(array_key_exists($key_to_match,$all_related_with_value))
193202
{
194-
if ($related->$query_key == $key_to_match)
203+
foreach ($all_related_with_value[$key_to_match] as $related)
195204
{
196-
$hash = spl_object_hash($related);
197-
198-
if (in_array($hash, $used_models))
199-
$model->set_relationship_from_eager_load(clone($related), $this->attribute_name);
200-
else
201-
$model->set_relationship_from_eager_load($related, $this->attribute_name);
202-
203-
$used_models[] = $hash;
204-
$matches++;
205+
if ($related->$query_key == $key_to_match)
206+
{
207+
$hash = spl_object_hash($related);
208+
209+
if (array_key_exists($hash, $used_models))
210+
$model->set_relationship_from_eager_load(clone($related), $this->attribute_name);
211+
else
212+
$model->set_relationship_from_eager_load($related, $this->attribute_name);
213+
214+
$used_models[$hash] = null;
215+
$matches++;
216+
}
205217
}
206218
}
207219

0 commit comments

Comments
 (0)