title: CakePHP 3 - Two foreach loops and associated models
body: <p>The database contains the following tables: <code>posts</code>, <code>posts_authors</code> and <code>users</code>.</p>
  
  <ul>
  <li><p><code>posts table fields</code>: <em>id</em>, <em>name</em>, <em>slug</em>, <em>content</em>, <em>created</em>, <em>modified</em>, <em>user_id</em> (record creator, not author), and <em>online</em>.</p></li>
  <li><p><code>posts_authors table fields</code>: <em>id</em>, <em>post_id</em> and <em>user_id</em>.</p></li>
  <li><p><code>users table fields</code>: <em>id</em>, <em>name</em>, <em>slug</em>, <em>email</em>, <em>password</em>, <em>country_id</em>, <em>avatar</em>, <em>created</em>, <em>modified</em>, and <em>status</em>.</p></li>
  </ul>
  
  <p>I'm trying to list all posts and all the authors for each post, but I don't know how to get the name of the users from their IDs in the second foreach loop.</p>
  
  <p><strong>CODE :</strong></p>
  
  <p><strong>My View</strong></p>
  
  <pre><code>&lt;?php foreach ($posts as $post): ?&gt;
  
      ...
  
      &lt;ul&gt;
      &lt;?php foreach ($post-&gt;authors as $authors): ?&gt;
          &lt;li&gt;&lt;?= $authors-&gt;users[0]-&gt;name ?&gt;&lt;/li&gt;
      &lt;?php endforeach; ?&gt;
      &lt;/ul&gt;
  
      ...
  
  &lt;?php endforeach; ?&gt;
  </code></pre>
  
  <p><strong>PostsAuthorsTable.php (Model)</strong></p>
  
  <pre><code>...
  
  $this-&gt;belongsTo('Users');
  $this-&gt;belongsTo('Posts');
  
  ...
  </code></pre>
  
  <p><strong>PostsTable.php (Model)</strong></p>
  
  <pre><code>...
  
  $this-&gt;belongsToMany('Users', [
      'through' =&gt; 'PostsAuthors',
  ]);
  
  ...
  </code></pre>
  
  <p><strong>UsersTable.php (Model)</strong></p>
  
  <pre><code>...
  
  $this-&gt;belongsToMany('Posts', [
      'through' =&gt; 'PostsAuthors',
  ]);
  
  ...
  </code></pre>
  
  <p><strong>PostsController.php (Controller)</strong></p>
  
  <pre><code>public function index()
  {   
      $posts = $this-&gt;Posts-&gt;find('all', [
          'conditions' =&gt; ['Posts.online !=' =&gt; -1]
      ])-&gt;order(['Posts.publication' =&gt; 'DESC'])-&gt;contain(['Users']);
  
      $this-&gt;set(compact(['posts']));
  }
  </code></pre>