tags:

views:

176

answers:

1

I'm new to Doctrine and ActiveRecord.

How should I filter a table after it has been loaded? (i suppose this is preferred over sending multiple queries?)

Is this 'good' or 'bad'?

class UserTable extends Doctrine_Table {
    function filterByGroup($group) {
        $ut = new UserTable();
        foreach($this as $u) {
            if($u->group == $group) $ut->add($u);
        }
        return $ut;
    }
}

Edit:

I understand there are built-in functions which provider 'filtering' functionality. But will the two following code-blocks perform differently regarding performance?

//1
$users = Doctrine_Core::getTable('Users')->findAll();
$admins = Doctrine_Core::getTable('Users')->findByGroupName('admin');
//2
$admins = Doctrine_Core::getTable('Users')->findByGroupName('admin');
$users = Doctrine_Core::getTable('Users')->findAll();
+2  A: 

First off, your if statement is assigning $u->group to $u, not comparing them. Watch out for = and == (and ===).

There are built in "findBy" functions available (see http://www.doctrine-project.org/Doctrine_Table/1_2#method_findby) to do what you want. You'll of course want to set up the appropriate indexes for the field you are filtering by.

On a side note, you should avoid using the word "group" as a field as it is an SQL keyword. At the very least, name it "group_name" or something.

Anyway, if I am understanding what you are trying to do, you don't even need to add a function in your UserTable class. You can get a filtered list of values directly from your script:

$users = Doctrine_Core::getTable('User')->findByGroupName($name);
Jody
sorry for the bad typos in the pseudo ;), replaced. Please see the updated question. What concerns me is the amount of queries that will be needed. If only 1 query is required it means that Doctrine automatically loads all records, and calls the findBy- function on it's inner results. This concerns me regarding large tables... However if multiple queries are used then my question remains valid, how to use the 'loaded' results in a table and really filter those?
Ropstah
The findBy method does not load all rows, it generates a WHERE clause based on the field and value you specify. I don't think it matters which order you make those calls, the performance should be the same. I thought there was a method in Doctrine_Collection to filter results, but I don't see it in the documentation at first glance.
Jody