【问题标题】:CakePHP 3 - Two foreach loops and associated modelsCakePHP 3 - 两个 foreach 循环和相关模型
【发布时间】:2015-11-26 22:26:50
【问题描述】:

该数据库包含以下表格:postsposts_authorsusers

  • posts table fields: id, name, slug, content, 已创建修改user_id(记录创建者,而非作者)和在线

  • posts_authors table fieldsidpost_iduser_id

  • users table fields: id, name, slug, email, 密码country_id头像创建修改状态 .

我正在尝试列出每个帖子的所有帖子和所有作者,但我不知道如何在第二个 foreach 循环中从他们的 ID 中获取用户的姓名。

代码:

我的观点

<?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(模型)

...

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

...

PostsTable.php(模型)

...

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

...

UsersTable.php(模型)

...

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

...

PostsController.php(控制器)

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

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

【问题讨论】:

  • 好吧,首先:如何在控制器中获取$posts 数组?那么如果 Post belogsToMany 用户应该是 $post-&gt;user 而不是 $post-&gt;author
  • @arilia 感谢您的评论!刚刚在我的问题中添加了PostsController.php

标签: php cakephp foreach cakephp-3.0


【解决方案1】:

已解决!

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

    ...

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

    ...

<?php endforeach; ?>

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多