-
-
Notifications
You must be signed in to change notification settings - Fork 46
Models
Models are classes that are meant to perform database actions, such as retreiving news posts or inserting comments. They are not meant to contain any output code, their only task is to query the database and return the results.
Models are completely optional since database queries can be done in the controllers too, but they are a good solution to separating database queries and actual page logic which helps to maintain a proper structure at a larger scale.
You are always connected to the CMS database via $this->db, however if you want to access the auth/logon database you need to retreive the connection by doing:
$db = $this->external_account_model->getConnection();
$db->query("SELECT * FROM ...");
To connect to the realms, you first need to retreive the specific realm object and then the connection of either world of characters:
$realm = $this->realms->getRealm(ID);
$worldDb = $realm->getWorld()->getConnection();
$characterDb = $realm->getCharacters()->getConnection();
Refer to the CodeIgniter documentation for database methods.
See the example model below:
<?php
class Items_model extends CI_Model
{
public function delete($id)
{
$this->db->query("DELETE FROM store_items WHERE id = ?", [$id]);
}
public function getItem($id)
{
$query = $this->db->query("SELECT * FROM store_items WHERE id = ? LIMIT 1", [$id]);
if($query->getNumRows() > 0)
{
$row = $query->getResultArray();
return $row[0];
}
else
{
return false;
}
}
}
You can also use query builder, see the example model below:
<?php
class Items_model extends CI_Model
{
public function delete($id)
{
$this->db->table('store_items')->where('id', $id)->delete();
}
public function getItem($id)
{
$query = $this->db
->table('store_items')
->select()
->where('id', $id)
->get()
if($query->getNumRows() > 0)
{
$row = $query->getResultArray();
return $row[0];
}
else
{
return false;
}
}
}