Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"User follows" with PropelORM - Three way relationship

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

like image 985
Kyle Goslan Avatar asked May 19 '15 01:05

Kyle Goslan


2 Answers

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>
like image 99
dened Avatar answered Oct 18 '22 14:10

dened


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) 
like image 23
Marc J. Schmidt Avatar answered Oct 18 '22 13:10

Marc J. Schmidt