Pages

Saturday, April 19, 2014

FuelCMS: Filter in a simple module using a join in list items.

FuelCMS provides a simple, yet powerful way to create models. When creating a model with a join to another table, the "_common_query" method should be overridden when extending the "Base_module_model" to create a query that joins both tables, in order to be able to filter data using data from the foreign table.


class Articles_model extends Base_module_model {
 public $filters = array('content', 'author_name'); 
 public $foreign_keys = array('author_id' => 'authors_model');

 function _common_query(){
  $this->db->join('authors', 'authors.id = articles.author_id', 'left');
  $this->db->select('articles.*', FALSE);
  parent::_common_query();
 }
}

In the above code, you are indicating that the model can be filtered by the articles content field, and the authors name field, which is being joined by populating the $foreign_key property.

The _common_query is overridden to create a query that will join both tables, which will give the ability to search items from fields from the external table.

Finally, to look for the articles written by a specific author name, you just need to call the fuel_model helper method.


fuel_model('articles', array('find' => 'all', 'where' => array('author_name' => 'Shakespeare')));


0 comments:

Post a Comment