Can someone point me in the right direction to do a “user follows” kind of thing. I have 3 tables: users, user_follows, and a posts.
If I hydrate a user object, I can get an array of users id’s they follow…and a post object knows which user posted it…but struggling to get posts for just the users that a given user follows.
Currently have this, which returns posts from everyone.
$posts = PostsQuery::create() ->orderByDate('desc') ->limit('12') ->find(); return $posts;
Need to do filterByXXX()…
Propel ORM doesn’t support many-to-many relationship between entities of the same table. But you can use EqualNestBehavior to get it working.
With this your code could look like this:
$user = UsersQuery::create()->findPk($userId); $follows = $user->getFollows(); $posts = PostsQuery::create() ->filterByUser($follows) ->orderByDate('desc') ->limit('12') ->find();
And here is the relevant part of schema:
<table name="follow"> <behavior name="equal_nest"> <parameter name="parent_table" value="users" /> </behavior> <!-- you do not need to specify any colums for the "follow" table, the behavior will add them automatically --> </table>
This is easily done using
$posts = PostsQuery::create() ->useUserFollowsQuery() ->filterByUserId([12,34,55]) ->endUse() ->orderByDate('desc') ->limit('12') ->groupById() //important if you join a one-to-many relation ->find(); return $posts;
Query optimized is to use addJoinCondition:
->innerJoinUserFollows() ->addJoinCondition('UserFollows', 'UserFollows.user_id = ?',[123,34], Criteria::IN)