Search code examples
phpormdoctrinedql

Doctrine query to update users table


I have a form with the following fields:

  • email
  • password
  • url
  • responsable
  • pais (this is a multicheckbox)
  • role

And I've created this method within the Model_Users class

public function updateUser($user) {
    $q = Doctrine_Query::create()
        ->update('Model_Users usr'); //aca estaba el ;

    foreach ($user as $k => $v) {
        if ($k == 'pais' || $k == 'id') {
            continue;
        } else {
            $q->set("usr.$k", '?', $v);
            //echo "Key: $k => Value: $v ||";
        }
    }

    $q->where("usr.id=$user[id]");
    $q->execute();
}

The problem is that this isn't really updating... and if I do something like echoing $q->getSqlQuery() the SQL query I get is UPDATE users SET email = ?, password = ?, url = ?, responsable = ?, role = ? WHERE (id = 150).

I'm guessing I cannot use a foreach loop to get this right,... so what would be the way around it?


Solution

  • If you already have a Model_User instance available then it should be for the record you are trying to update. Otherwise you just use a query. The updateUser doesnt belong on Model_User it belongs on Model_User_Table assuming you are actually generating the Doctrine table classes for each model (which i personally recommend).

    To answer your actual question though it shoudl look something like this:

       $q = Doctrine_Query::create()
            ->update('Model_Users');
    
       foreach ($user as $k => $v) {
            if ($k == 'pais' || $k == 'id') {
                continue;
            } else {
                $q->set($k, $v);
            }
        }
    
        $q->where("usr.id = ?", $user[id]);
        $q->execute();
    

    As for setting pais that code is goign to depend on how pais is stored in the DB (what doctrine type is it - array, object, string, M2m relation?).