迭代不返回所有值CakePhp

问题描述 投票:1回答:1

我试图得到一个帐户所关注的用户的所有帖子。我有一个查询,检查当前用户正在关注谁工作正常(返回下面的所有值|代码)。

 $followersTable=TableRegistry::get('Followers');
 $all_following = $followersTable->find('all')->where(['follower_fk'=>$this->Auth->User('id')])->toArray();

问题是,当我尝试获取帖子时,我只收到一个用户的帖子。有什么可能是问题的建议吗?

$all_posts_following = NULL;

        foreach($all_following as $follower)
        {
            $postsTable=TableRegistry::get('Posts');
            $all_posts_following = $postsTable->find('all')->where(['Posts.user_fk' => $follower[('followed_fk')]])->toArray();
        }

        $this->set("all_posts_following",$all_posts_following); 
cakephp foreach cakephp-3.0
1个回答
1
投票

您正在覆盖分配给all_posts_following的先前值。

如果要追加到数组,请使用array_merge

    $all_posts_following = [];
    $postsTable = TableRegistry::get('Posts');
    foreach($all_following as $follower)
    {
        $posts = $postsTable->find('all')->where(['Posts.user_fk' => $follower[('followed_fk')]])->toArray();
        $all_posts_following = array_merge($all_posts_following, $posts);
    }

    $this->set("all_posts_following",$all_posts_following); 

或者,您可以使用IN运算符查询所有匹配项。

    $postsTable = TableRegistry::get('Posts');
    $all_posts_following = $postsTable->find('all')
       ->where(['
           Posts.user_fk IN' => $all_following
    ])->toArray();

请记住,当您调用toArray()时,MySQL驱动程序会将所有记录读取到内存中,然后再发送到视图。如果您知道您只是迭代(循环)记录,那么将查询传递给视图并在foreach中使用它。

© www.soinside.com 2019 - 2024. All rights reserved.