views:

314

answers:

2

I've set up a new database config in application/config/database.php called staff.

I've then made a new base model, and added a protected $db variable and set it in the constructor to $this->db = Database::instance('staff').

When I try and replace Db::query(Database::SELECT, $query) with $this->db->query(Database::SELECT, $query), it fails with...

Missing argument 3 for Kohana_Database_MySQL::query()

The 3rd argument I am missing is $as_object, which is not required when using the static query() method. My guess is the static method passes this in for me. It actually returns new Database_Query($type, $sql).

I think I am doing it wrong.

Is there a way to overload the static Db::query() I usually use in different classes with the alternate database configuration?

Thanks

+4  A: 

I've then made a new base model, and added a protected $db variable and set it in the constructor to $this->db = Database::instance('staff').

You have loaded a database in your controller.

When I try and replace Db::query(Database::SELECT, $query) with $this->db->query(Database::SELECT, $query), it fails with...

Now you are creating a query.

Next, you need to execute the query using the database you have created:

$result = $query->execute($this->db);

In Kohana v3, queries and databases are separated, so you have to tell the query which database to execute on, rather than telling the database to execute a query. The query will compile itself, then call $db->query($sql) itself.

You can also shortcut around loading the database:

$query->execute('staff');

Which will execute on the "staff" database.

shadowhand
Thanks Shadowhand!
alex
A: 

Using Shadowhand's answer, I made this in my base model to ease queries to my database

protected function query($type, $query) {

   $query = new Database_Query($type, $query);

   return $query->execute('staff')->as_array();
}
alex