Improving laravel relationship performance

This commit is contained in:
Vinícius Fragoso 2012-10-05 10:35:48 -03:00
parent 4f8a6724b0
commit f36446bd10
4 changed files with 40 additions and 24 deletions

View File

@ -87,16 +87,17 @@ public function match($relationship, &$children, $parents)
{ {
$foreign = $this->foreign_key(); $foreign = $this->foreign_key();
foreach ($children as &$child) $parents_hash = array();
foreach ($parents as $parent)
{ {
$parent = array_first($parents, function($k, $v) use (&$child, $foreign) $parents_hash[$parent->get_key()] = $parent;
{ }
return $v->get_key() == $child->$foreign;
});
if ( ! is_null($parent)) foreach ($children as $child)
{
if (array_key_exists($child->$foreign, $parents_hash))
{ {
$child->relationships[$relationship] = $parent; $child->relationships[$relationship] = $parents_hash[$child->$foreign];
} }
} }
} }

View File

@ -91,14 +91,18 @@ public function match($relationship, &$parents, $children)
{ {
$foreign = $this->foreign_key(); $foreign = $this->foreign_key();
foreach ($parents as &$parent) $children_hash = array();
foreach ($children as $child)
{ {
$matching = array_filter($children, function($v) use (&$parent, $foreign) $children_hash[$child->$foreign][] = $child;
{ }
return $v->$foreign == $parent->get_key();
});
$parent->relationships[$relationship] = array_values($matching); foreach ($parents as $parent)
{
if (array_key_exists($parent->get_key(), $children_hash))
{
$parent->relationships[$relationship] = $children_hash[$parent->get_key()];
}
} }
} }

View File

@ -328,14 +328,18 @@ public function match($relationship, &$parents, $children)
{ {
$foreign = $this->foreign_key(); $foreign = $this->foreign_key();
foreach ($parents as &$parent) $children_hash = array();
foreach ($children as $child)
{ {
$matching = array_filter($children, function($v) use (&$parent, $foreign) $children_hash[$child->pivot->$foreign][] = $child;
{ }
return $v->pivot->$foreign == $parent->get_key();
});
$parent->relationships[$relationship] = array_values($matching); foreach ($parents as $parent)
{
if (array_key_exists($parent->get_key(), $children_hash))
{
$parent->relationships[$relationship] = $children_hash[$parent->get_key()];
}
} }
} }

View File

@ -38,14 +38,21 @@ public function match($relationship, &$parents, $children)
{ {
$foreign = $this->foreign_key(); $foreign = $this->foreign_key();
foreach ($parents as &$parent) $children_hash = array();
foreach ($children as $child)
{ {
$matching = array_first($children, function($k, $v) use (&$parent, $foreign) if (array_key_exists($child->pivot->$foreign, $children_hash))
{ {
return $v->$foreign == $parent->get_key(); continue;
}); }
$parent->relationships[$relationship] = $matching; $children_hash[$child->pivot->$foreign] = $child;
}
foreach ($parents as $parent)
{
if (array_key_exists($parent->get_key(), $children_hash))
$parent->relationships[$relationship] = $children_hash[$parent->get_key()];
} }
} }