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:
<?php 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'); //OR $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('Article.id')));
records will be returned in an associative array, you can use the quick pr() function to check the variable contents:
pr($articles)
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 //OR $deleted = $this->Article->deleteAll(array('title LIKE' => '%spam%'));