Search code examples
phpdoctrine-ormdql

Which is faster? Iteration or DQL?


Which of these is faster?

Given that I have already done the following...

$query = $em->createQuery("SELECT g FROM SSMURBS\Group g WHERE g.id = {$_POST['group_id']}");
$group = $query->getSingleResult();

Which of the following lines of code is best?

(1)

$query = $em->createQuery("SELECT partial p.{id} FROM SSMURBS\Person p WHERE :groupId MEMBER OF p.groups");
$query->setParameter('groupId', $_POST['group_id']);
$member_ids_result = $query->getScalarResult();
$member_ids = $member_ids_result[0];

or...

(2)

$group_member_ids = array();
foreach( $group->members as $member ){
    $group_member_ids[] = $member->id;
}

Solution

  • Both methods seem to do two different things.

    • The first gets all and populates $member_ids with the first result.
    • The second iterates through each member in the group

    The best way to iterate through results is to use the query's iterate() method. See docs ->

    $query = $em->createQuery("SELECT g FROM SSMURBS\Group g WHERE g.id = ?1");
    $query->setParameter(1, $_POST['group_id']);
    
    $group_member_ids = array();
    $iterableResult = $query->iterate();
    
    foreach ($iterableResult as $member) {
        $group_member_ids[] = $member->id;
    }
    

    Like I said in my comment on your question, validate user input before using in the query. Just to be safe.