1

I have just started learning cakephp3, so please excuse me for anything wrong. So I have three tables called Users, Projects and Events, so there relation is like, one user can hasmany projects and one project can has many events.

if i access the basic url

testap/events

I want only those events to appear in the list which belongs to the logged-in user. Note: Event table has only project id not user id and project table has user id.

Consider the following scenarios

Projcts Table

ID User_id
1 1
2 1
3 2
4 3

Events Table

ID Project_id
1 1
2 1
3 1
4 2
5 2
6 3
7 4

So I want only to display events 1to5 as they belong to the logged-in user (say user with id 1 has logged in)

Please tell how can I achieve this?

Thanks in advance

2

1 Answer 1

1

The new cake 3 orm is fantastic for something like this.

// You can replace $this->Users with TableRegistry::get('users') 
// if not in the users controller
$user = $this->Users->find($this->Auth->user('id'), [
    'contain' => [
        'Projects.Events'
    ]
]);

You can get your events like this

$user->projects[0]->events;

Or if you get want to get events for a specific user you can do it backwards

$events = $this->Events->find()->matching('Projects.Users', function ($query) use ($userId) {
    return $query->where(['user_id' => $userId]);
});

I am assuming you have defined in your UsersTable initialize function

$this->hasMany('Projects');

And in your ProjectsTable

$this->hasMany('Events');
$this->belongsTo('Users');

And in your events table

$this->belongsTo('Projects');
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.