"User follows" with PropelORM - Three way relationship
Asked Answered
R

2

16

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()...

Remediosremedy answered 19/5, 2015 at 1:5 Comment(2)
try this: groups.google.com/forum/#!topic/propel-development/UG-7T3dK2WgUntitled
Definitely helped me out. Pointed me in the right direction, thanks!Remediosremedy
D
1

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>
Dehydrogenase answered 28/5, 2015 at 8:48 Comment(0)
G
1

This is easily done using use*Query.

$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) 
Geosphere answered 28/6, 2015 at 0:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.