迭代不返回所有值CakePhp

时间:2017-12-17 14:35:40

标签: cakephp foreach cakephp-3.0

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

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

1 个答案:

答案 0 :(得分:1)

您正在覆盖分配给Picasso.with(getBaseContext()).load(tempUser.getPhotoUrl()).fetch(); 的上一个值。

如果要附加到数组,请使用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(); 时,MySQL驱动程序会将所有记录读入内存,然后再发送到视图。如果您知道您只是要迭代(循环)记录,那么将查询传递给视图并在toArray()中使用它。