mysql
DB Structure
mysql
DB Structure
IndexesController.php
class IndexesController extensions AppController {
public$uses=['Article'];
public function index() {
$indexArticles=$this->Article->find('all',array(
'fields' = > array('article_title', 'article_url', 'pub_date',
'order'=>array('pub_date'=>'desc'),
'limit' = > 50
));
$this->set('indexArticles', $indexArticles);
}
}
Indexes/index.ctp
<table>
<tr>
<th>Update Time</th>
<th> Article Title </th>
</tr>
<?php
foreach($indexArticles as$data){
$title=$data['Article']['article_title'];
$link=$data['Article']['article_url'];
$pub_date=$data['Article']['pub_date'];
echo'<tr>';
echo'<td>'.$pub_date.'</td>';
echo'<td><a href="'.$link." target="_blank">'.$title.'</a></td>';;
echo'</tr>';
}
?>
</table>
You have obtained article information from Articles.
Now we have a list of articles on the index page.
The purpose is to use the cakephp association to display the site name for these article links.
If you imagine an antenna site like http://kita-kore.com/, it would be easy to understand.
After studying all the cakephp tutorials, I imagine that I might use the association $hasMany
, but I don't know how to build it.
Is it nonsense to use the controller as IndexesController.php in the first place?
I don't even understand if I write what I want to do in SitesController.php.
I look forward to hearing from you.
php cakephp
In this case, the relationship between the models is Site "hasMany" Article
, Article "belongsTo" Site
.
In IndexesController, you want to display the Site associated with the Article, so set the BelongsTo association to the Article model.
http://book.cakephp.org/2.0/ja/models/associations-linking-models-together.html#belongsto
<?php
class Article extensions Model {
// ...(snip)
public$belongsTo=[
'Site' = > [
'className' = > 'Site',
'foreignKey' = > 'site_id',
],
];
// ...(snip)
}
Add Site.site_name
, Site.site_url
to fields
when retrieving on the controller side.
$indexArticles=$this->Article->find('all',array(
'fields' = > array('Article.article_title', 'Article.article_url', 'Article.pub_date', 'Site.site_name', 'Site.site_url'),
'order'=>array('pub_date'=>'desc'),
'limit' = > 50
));
Now,
[
['Article'=>['article_name'=>...], 'Site'=>['site_name'=>...],
['Article'=>[...], 'Site'=>[...]],
]
You can retrieve data in the form shown in .
Because the value is echoed in View, if the article title or URL has an HTML tag, it will appear as it is, which is an XSS vulnerability.
Use the HtmlHelper::link
or escape through the h()
function.
<table>
<tr>
<th>Update Time</th>
<th> Article Title </th>
</tr>
<?php foreach($indexArticles as$data): ?>
<tr>
<td><?phpechoh($data['Article']['pub_date']);?>/td>
<td><?phpecho$this->Html->link($data['Article']['article_title'],$data['article']['article_url'],['target'=>'_blank']);?>>>>
</tr>
<?php endforeach;?>
</table>
© 2024 OneMinuteCode. All rights reserved.