Foreign keys
If in a model the "enum" field is used, then the list of its values can be taken from other model. Such an interconnection is built on the basis of foreign keys.
Binding example between news and comments, each comment belongs to specific news article and is connected to it by the foreign key.
class News extends Model { protected $name = "News"; protected $model_elements = array( array("Activate", "bool", "active", array("on_create" => true)), array("Name", "char", "name", array("required" => true)), array("Date", "date_time", "date", array("required" => true)), array("Content", "text", "content", array("rich_text" => "true")), array("Comments", "many_to_one", "comments", array("related_model" => "Comments")) ); ); class Comments extends Model { protected $name = "News comments"; protected $model_elements = array( array("Activate", "bool", "active", array("on_create" => true)), array("Date", "date_time", "date", array("required" => true)), array("Name", "char", "name", array("required" => true)), array("News", "enum", "news_id", array("foreign_key" => "News")), array("Content", "text", "content") ); );
The News model has Comments field of Many to one type in order to see the number of comments for each news article, and also to move quickly to the model of comments with the filtered records related to this news page.
Display records by foreign key
Let's assume that news are shown with URL like "/news /25/". In the file "config/routes.php" a route as "news/*/" => "view-news.php" has been created.
//The content of view-news.php file <? $url_part = $mv -> checkUrlPart(2, "numeric"); $news_record = $mv -> news -> findRecord(array("active" => 1, "id" => $url_part)); $mv -> display404($news_record); $mv -> seo -> mergeParams($news_record -> name." ".I18n :: formatDate($news_record -> date)); include $mv -> views_path."main-header.php"; ?> <div id="content"> <div class="date"> <? echo I18n :: formatDate($news_record -> date); ?> </div> <h1><? echo $news_record -> name; ?></h1> <? echo $news_record -> content; ?> <div id="comments"> <h3>Comments: <? echo $mv -> comments -> countRecords(array("active" => 1, "news_id" => $news_record -> id)); ?> </h3> <? echo $mv -> comments -> display($news_record -> id); ?> </div> </div> <? include $mv -> views_path."main-footer.php"; ?>
Let’s add a function to display comments for model “Comments”.
class Comments extends Model { ... public function display($news_id) { $html = ""; $rows = $this -> select(array("active" => 1, "order->desc" => "date", "news_id" => $news_id)); foreach($rows as $row) { $html .= "<p class='date'>".$row["name"]." ".I18n :: formatDate($row["date"])."</p>"; $html .= "<p>".$row["content"]."</p>"; } return $html; } }
Previous section
Simple models