Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Fetching related model entries of all related entries

Hi,

I am trying to make a twitter clone. Thanks to the wonders of MVC, after setting up the models relationships getting related entries has become really simple. For instance, getting all the posts of a single user for the users page is as simple as:

$posts = $user->getPosts();

I have run into a problem when I got to the homepage part where I'm supposed to show all the latest posts of the followed users. I can get all the followed users:

$followers = $user->getFollowers();

But what I need is the next step, all their posts. Something along the lines of:

$posts = $user->getFollowers()->getPosts();

Any help would be much appreciated.



107.4k
Accepted
answer

You shouldn't use those methods FOR DISPLAYING. Use query builder imho, select columns only which you won't, don't work on full model objects etc.



772

You shouldn't use those methods FOR DISPLAYING. Use query builder imho, select columns only which you won't, don't work on full model objects etc.

Thank you.

edited Jul '16

So basically after getting all followers you can create some array of ids of those follower and then just find posts where follower id IN this array. Also think about selecting data you only need, and working on arrays(lower memory consumption, faster) etc.



772

I have changed everything to be done by the querybuilder. I am stuck on the same part now. How do I store the results of an executed query as an array?

Using toArray() method



772

I did it, it works now. Thank you!