php - CakePHP 3 : How to display associated data for each record in index. CTP?

标签 php mysql cakephp

我有两个表 artistspictures ,并且具有 artist hasMany Paintings 关系。

而不是为每个显示相关图片的艺术家提供单独的 view.ctp。我只想显示 index.ctp 文件中列出的所有艺术家以及每个相关图片(ID 列表)中的所有内容。

读完食谱和无数的帖子后,我完全困惑了,不明白我该怎么做。 (我对 PHP 和 Cakephp 还很陌生)

在单个艺术家的 view( ) 函数中,我可以轻松获取相关图片,如下所示:

Controller :ArtistsController.php

..
public function view($id=null)
{
   $artist = $this->Artists->get($id, [
      'contain' => ['Paintings']
   ])
...
}

然后通过执行以下操作获取相应view.ctp中的所有内容:

view.ctp
<?php foreach ($artist->paintings as $paintings): ?>
<ul><li> <?= h($paintings->id) ?> </li></ul>
....
<?php endforeach; ?>

但是我该如何为表中列出的每个艺术家的 index.ctp/index() 函数执行类似的操作呢?所以我基本上可以拥有这样的东西:

<?php foreach ($artists as $artist): ?>
    <tr><td> <?= h($artist->name) ?> </td></tr>
    <tr><td> <?php foreach ($artist->paintings as $paintings): ?>
             <ul><li> <?= h($painting->id) ?> </li></ul>
             <?php endforeach; ?>
    </tr></td>
<?php endforeach; ?>

我知道它并不是真的那样工作,但我该如何去做呢? 我是否必须在 Controller index() 函数中使用 find() 查询并在 View 中检索结果之前存储结果?!我确实尝试过,但它要么什么也不显示,要么显示 SQL 查询本身,因为我以某种方式弄乱了语法...

因此,在尝试了书中的各种内容并搜索了几个小时之后,我的大脑似乎缺少一些基本的理解。我发现的所有类似问题也让我一无所获。

即使是一个提示从哪里开始也很棒!非常感谢!

最佳答案

好的,我可以理解,我给你一个例子,它可能对你有帮助

两个表 1) 艺术家 2) 图片

艺术家有 2 个字段id,name
而图片有3个字段id,artist_id,picture//这里artist_id建立了艺术家和图片的关系。

这里Artists和图片有很多关系,所以我们写在Model\Table\ArtistsTable.php

 public function initialize(array $config)
 {
        parent::initialize($config);

        $this->table('artists');
        $this->displayField('name');
        $this->primaryKey('id');

        $this->hasMany('Pictures', [
            'foreignKey' => 'artist_id'
        ]);
 }

然后Controller\ArtistsController.php index方法应该像下面的代码

public function index()
{
        $this->paginate =[
            'contain'   => ['Pictures']   //with artists We also fetch pictures
        ];
        $this->set('artists', $this->paginate($this->Artists));
        $this->set('_serialize', ['artists']);
}

现在在 Template\Artists\index.ctp 中,您可以像下面的代码一样获取数据

<?php foreach ($artists as $artist): ?>
    <?= h($artist->name) ?>  // fetch artists name from artists table 
  <?php foreach ($artist->pictures as $pictures): ?>  
    <?= h($pictures->picture) ?>  // fetch pictures according to artists 
  <?php endforeach; ?>
<?php endforeach; ?>

现在你会得到类似的输出

jondu 1 2 3

这里 jondu 是一个名字,他有 3 张图片 1,2,3。

关于php - CakePHP 3 : How to display associated data for each record in index. CTP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33219617/

相关文章:

php - 更新到 Symfony 3.0 时找不到类 'Appkernel'

php - 如何使用 CodeIgniter 中的下拉列表在 HTML 表中显示过滤后的数据库值?

php - phpunit 中的模拟类

php - 如何在 XML 文件中连接相似的标签

php - 将Mysql程序转换为PHP代码

php - 插入带有 Select 和附加参数的 stmt

php - CakePHP 3.0 - 在实体中使用 MySQL 函数

python - django.db.utils.OperationalError : (1046, 'No database selected' )

mysql - 如何从 CakePHP 中的表名获取模型名称

php - 使用 cakephp 从数据库中推荐单词