Skip to content

Commit

Permalink
added Model::query() method for running arbitrary queries
Browse files Browse the repository at this point in the history
YourModel::query("delete from users where name=?",array('bob'));
  • Loading branch information
kla committed May 31, 2010
1 parent 56236f6 commit 155078f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/Model.php
Expand Up @@ -1478,6 +1478,18 @@ public static function find_by_sql($sql, $values=null)
return static::table()->find_by_sql($sql, $values, true);
}

/**
* Helper method to run arbitrary queries against the model's database connection.
*
* @param string $sql SQL to execute
* @param array $values Bind values, if any, for the query
* @return object A PDOStatement object
*/
public static function query($sql, $values=null)
{
return static::connection()->query($sql, $values);
}

/**
* Determines if the specified array is a valid ActiveRecord options array.
*
Expand Down
9 changes: 9 additions & 0 deletions test/ActiveRecordTest.php
Expand Up @@ -469,5 +469,14 @@ public function test_id_setter_works_with_table_without_pk_named_attribute()
$author = new Author(array('id' => 123));
$this->assert_equals(123,$author->author_id);
}

public function test_query()
{
$row = Author::query('SELECT COUNT(*) AS n FROM authors',null)->fetch();
$this->assert_true($row['n'] > 1);

$row = Author::query('SELECT COUNT(*) AS n FROM authors WHERE name=?',array('Tito'))->fetch();
$this->assert_equals(array('n' => 1), $row);
}
};
?>

0 comments on commit 155078f

Please sign in to comment.