迭代不返回所有值 CakePhp

Iteration not returning all values CakePhp

我正在尝试获取某个帐户关注的用户的所有帖子。我有一个查询,它检查当前用户正在关注谁,这工作正常(returns 所有值 | 下面的代码)。

 $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); 

您正在覆盖之前分配给 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();

Keep in mind that when you call toArray() that all of the records are read by the MySQL driver into memory before being sent to the view. If you know that you're only going to iterate (loop) the records, then pass the query to the view and use it in a foreach.