Trying to download all messages from users that the user is executing in Cakey mode.
Three tables:
users (id, username, password)
messages (id, text, user_id, created)
follows (id, user_id, follow_id)
I think my relationship is set up correctly, so I can download followers of users and people following them:
User 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' ]);
According to table
$this->belongsTo('Users', [ 'foreignKey' => 'user_id', 'joinType' => 'INNER' ]);
Message table
$this->belongsTo('Users', [ 'foreignKey' => 'user_id', 'joinType' => 'INNER' ]);
Now, trying to select all messages from users that follow one user. I think I need to use the matching() method described here: Filtering by related data through matching and joining , but it doesn't seem to be right,
Try something in this direction:
$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 my relationship is set correctly, this search will return the user along with all the users that they follow:
$users = $this->Posts->Users->get(1, [ 'contain' => ['Following'] ]);