CakePHP 在不同的模板上使用模型和控制器



我已经按照文档创建了表、实体、控制器,然后是模板来显示数据。在我的/文章网站上,我现在想显示用户数据。因此,我的用户数据将在/articles而不是/users上。

在/templates/Articles/index.php中,我现在可以使用$articles,但不能使用$users。如何在我的页面中使用另一个控制器?

我的目标是为发布文章的用户电子邮件添加一行。

ArticlesController.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; ?>

我ArticlesTable.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);
}
}
}

最新更新