Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/chronocm/public_html/libs/str.php on line 17
ChronoCMS - Simple and powerful CMS - Working with models

Working with models

Models classes provide an easy way to work with your database tables, and instead of writing plain SQL syntax which may be harder to read and write, not compatible on different database engines or not secure enough, the Model handle this easily for you, a simple model may contain the associated table name only, e.g:

namespace GCore\Admin\Models;
defined("GCORE_SITE") or die;
class Article extends \GCore\Libs\Model {
  var $tablename = '#__articles';

The model defined above can help us work easily with the articles table, the class has some useful methods and properties which can be used, here are few examples covering the most used ones:

Retrieving data:

First, here are the different ways to use your model classes:

//loading a model instance and selecting all articles
$articles = \GCore\Admin\Models\Article::getInstance()->find('all');
$article = new \GCore\Admin\Models\Article();
$articles = $article->find('all');
//OR inside your controller
var $models = array('\GCore\Admin\Models\Article');
//then inside any function:
$articles = $this->Article->find('all');
And more find examples:
//number of articles
$articles = $this->Article->find('count');
//number of published articles
$articles = $this->Article->find('count', array('conditions' => array('Article.published' => 1)));
//first article (limit 1)
$article = $this->Article->find('first');
//order by
$articles = $this->Article->find('all', array('order' => array('')));

records will be returned in an associative array, you can use the quick pr() function to check the variable contents:


You may also retrieve the value of a single column:

$title = $this->Article->field('title', array('id' => 123));

Deleting Data:

$deleted = $this->Article->delete(123); //delete the article with id = 123
$deleted = $this->Article->deleteAll(array('title LIKE' => '%spam%'));