phpcakephpforeachcakephp-3.0

Iteration not returning all values CakePhp


I am trying to get all the posts of the users an account is following. I have a query which checks who the current user is following which works fine(returns all values | code below).

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

The problem is when I try to get the posts, I get the posts of only one user. Any suggestions on what might be the problem please ?

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

Solution

  • You are overwriting the previous value assigned to all_posts_following.

    Use array_merge if you want to append to the array.

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

    Alternatively, you can just query for all the matches using the IN operator.

        $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.