CakePHP 3 - Load posts from users a user is following

Viewed 311

Trying to load all posts from users a user is following in a "Cakey" way.

Three tables:

users (id, username, password)

posts (id, text, user_id, created)

follows (id, user_id, following_id)

I think my relationships are set up correctly, so I can load a users followers and the people following them:

Users Table

    $this->belongsToMany('Following', [
        'className' => 'Users',
        'foreignKey' => 'user_id',
        'targetForeignKey' => 'following_id',
        'joinTable' => 'follows'
    ]);

    $this->belongsToMany('Followers', [
        'className' => 'Users',
        'foreignKey' => 'following_id',
        'targetForeignKey' => 'user_id',
        'joinTable' => 'follows'
    ]);

Follows Table

    $this->belongsTo('Users', [
        'foreignKey' => 'user_id',
        'joinType' => 'INNER'
    ]);

Posts Table

    $this->belongsTo('Users', [
        'foreignKey' => 'user_id',
        'joinType' => 'INNER'
    ]);

Now struggling to select all the posts from the users a single user follows. Think I need to use the matching() method documented here: Filtering by Associated Data Via Matching And Joins but don't seem to be getting it right.

Trying something along these lines:

$user_id = $this->Auth->user('id');

$posts = $this->Posts->find()->matching('Users.Following', function ($q)  use ($user_id)  {
      return $q->where(['Users.id' => $user_id]);
})->all();

UPDATE:

I think I have my relationships set up correctly, this find will return the user, along with all the users they are following:

  $users = $this->Posts->Users->get(1, [
      'contain' => ['Following']
  ]);
2 Answers
Related