Foreign key relation
If a model uses an enum field, its list of values can be data from another model. Such a relationship is built on the basis of foreign keys.
An example of a relationship between news and comments, each comment refers to a specific news item and is linked to it by a foreign key.
class News extends Model
{
protected $name = 'News';
protected $model_elements = [
['Activate', 'bool', 'active', ['on_create' => true]],
['Title', 'char', 'name', ['required' => true]],
['Date', 'date_time', 'date', ['required' => true]],
['Content', 'text', 'content', ['rich_text' => 'true']],
['Comments', 'many_to_one', 'comments', ['related_model' => 'Comments']]
];
}
class Comments extends Model
{
protected $name = 'Comments';
protected $model_elements = [
['Activate', 'bool', 'active', ['on_create' => true]],
['Date', 'date_time', 'date', ['required' => true]],
['Name', 'char', 'name', ['required' => true]],
['News', 'enum', 'news_id', ['foreign_key' => 'News']],
['Contents', 'text', 'content']
];
}
The News model has a Comments field of the Many to One type, so that you can see the number of comments for each news item, as well as quickly go to the Comments model with filtered records related to this news item.
Displaying records by foreign key
Let's assume that all news items are displayed by the URL /news, and a single news item by a URL like /news/25.
//Config/routes.php file
'/news' => 'view-news-all.php',
'/news/*' => 'view-news-detailed.php',
<?
//File views/view-news-detailed.php
$url_part = $mv -> checkUrlPart(2, 'numeric');
$news_record = $mv -> news -> find(['active' => 1, 'id' => $url_part]);
$mv -> display404($news_record);
$mv -> seo -> mergeParams($news_record -> name.' '.I18n::formatDate($news_record -> date));
$total = echo $mv -> comments -> countRecords(['active' => 1, 'news_id' => $news_record -> id]);
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 $total; ?></h3>
<? echo $mv -> comments -> display($news_record -> id); ?>
</div>
</div>
<? include $mv -> views_path.'main-footer.php'; ?>
Adding the function to display comments for the Comments model.
<?
class Comments extends Model
{
...
public function display(int $news_id): string
{
$html = '';
$rows = $this -> select(['active' => 1, 'news_id' => $news_id, 'order->desc' => 'date']);
foreach($rows as $row)
{
$html .= '<div class="date">'.$row['name'].' '.I18n::formatDate($row['date']).'</div>';
$html .= '<p>'.$row['content'].'</p>';
}
return $html;
}
}
Previous section
Simple models