CakePHP 3:如何在index.ctp中显示每条记录的关联数据?

eve*_*eve 2 php mysql cakephp

我有两张桌子artists并且picturesartist hasMany paintings关系.

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

在阅读了食谱和大量的线程后,我完全感到困惑,不明白我该怎么做.(我还是PHP和Cakephp的新手)

view( )单一艺术家的功能中,我可以像这样轻松获得相关图片:

控制器:ArtistsController.php

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

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

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

但是,如何为表中列出的每个艺术家的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; ?>
Run Code Online (Sandbox Code Playgroud)

我知道这不是那样的,但我该怎么做呢?我是否必须在Controllers index()函数中使用find()查询并在视图中检索结果之前存储结果?!我确实尝试过,但它没有显示任何内容,或者它显示了一个SQL查询本身,因为我搞砸了语法...

因此,在尝试了书中的各种事情并搜索了几个小时之后,似乎我在这里缺少一些基本的理解.我发现的所有类似问题都让我一无所获.

甚至暗示从哪里开始这将是伟大的!非常感谢!

Ali*_*rim 5

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

two table 1) artists 2) pictures.

艺术家有2个领域id,name
和图片有3个领域id,artist_id,picture //这里artist_id已经建立了艺术家和图片之间的关系.

艺术家与图片有很多关系,所以我们会写 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'
        ]);
 }
Run Code Online (Sandbox Code Playgroud)

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

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

现在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; ?>
Run Code Online (Sandbox Code Playgroud)

现在你得到的输出就像

jondu 1 2 3
Run Code Online (Sandbox Code Playgroud)

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