[英]CakePHP use Model & Controller on different Template
我已经按照文档创建了表、实体、控制器,然后是显示数据的模板。 在我的 /articles 站点上,我现在想显示用户数据。 所以我的用户数据将在 /articles 而不是 /users 上。
在 /templates/Articles/index.php 我现在可以使用$articles
,但不能使用$users
。 如何在我的页面中使用另一个控制器?
我的目标是在发布文章的用户电子邮件中添加一行。
文章控制器.php
public function index(){
$articles = $this->Paginator->paginate($this->Articles->find());
$users = $this->Articles->Users->find('')->all()->first();
$this->set('users', $users);
$this->set(compact('articles'));
}
我的模板/文章/index.php
<?php foreach ($articles as $article): ?>
<tr>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', $article->slug]) ?>
</td>
<td>
a
</td>
<td>
<?php echo $article->$users ?>
</td>
<td>
<?= $this->Html->link('Edit', ['action' => 'edit', $article->slug]) ?>
</td>
<td>
<?= $this->Form->postLink(
'Delete',
['action' => 'delete', $article->slug],
['confirm' => 'Are you sure?']) ?>
</td>
</tr>
<?php endforeach; ?>
我的文章表.php
class ArticlesTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp');
$this->belongsToMany('Tags');
$this->hasOne('Users');
}
public function beforeSave(EventInterface $event, $entity, $options)
{
if ($entity->isNew() && !$entity->slug) {
$sluggedTitle = Text::slug($entity->title);
// trim slug to maximum length defined in schema
$entity->slug = substr($sluggedTitle, 0, 191);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.