Benoda
Benoda

Reputation: 133

CakePHP 3 - Two foreach loops and associated models

The database contains the following tables: posts, posts_authors and users.

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.

CODE :

My View

<?php foreach ($posts as $post): ?>

    ...

    <ul>
    <?php foreach ($post->authors as $authors): ?>
        <li><?= $authors->users[0]->name ?></li>
    <?php endforeach; ?>
    </ul>

    ...

<?php endforeach; ?>

PostsAuthorsTable.php (Model)

...

$this->belongsTo('Users');
$this->belongsTo('Posts');

...

PostsTable.php (Model)

...

$this->belongsToMany('Users', [
    'through' => 'PostsAuthors',
]);

...

UsersTable.php (Model)

...

$this->belongsToMany('Posts', [
    'through' => 'PostsAuthors',
]);

...

PostsController.php (Controller)

public function index()
{   
    $posts = $this->Posts->find('all', [
        'conditions' => ['Posts.online !=' => -1]
    ])->order(['Posts.publication' => 'DESC'])->contain(['Users']);

    $this->set(compact(['posts']));
}

Upvotes: 1

Views: 2076

Answers (1)

Benoda
Benoda

Reputation: 133

SOLVED!

<?php foreach ($posts as $post): ?>

    ...

    <ul>
    <?php foreach ($post->users as $user): ?>
        <li><?= $user->name ?></li>
    <?php endforeach; ?>
    </ul>

    ...

<?php endforeach; ?>

Upvotes: 1

Related Questions