Reputation: 133
The database contains the following tables: posts
, posts_authors
and users
.
posts table fields
: id, name, slug, content, created, modified, user_id (record creator, not author), and online.
posts_authors table fields
: id, post_id and user_id.
users table fields
: id, name, slug, email, password, country_id, avatar, created, modified, and status.
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
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