Possible to have BelongsToMany through BelongsToMany in one model?

Hello I have 5 tables.
Instances (Model in question)
InstancesUserGroups (Join Table)
UsersUserGroups (Join Table)
Users (Table which I need to load into Model in question)



Issue: trying to load Users from Instances Model

My BelongsToMany for UserGroups works just fine:

$this->belongsToMany(‘UserGroups’, [
‘foreignKey’ => ‘instance_id’, //instances - primary id
‘targetForeignKey’ => ‘ug_id’, //user_groups - primary id
‘joinTable’ => ‘insatnces_user_groups’,
‘through’ => ‘InsatncesUserGroups’

But not sure how to create BelongsToMany for Users, here is what i currently have:

$this->belongsToMany('Users', [
    'foreignKey' => 'ug_id', //instances - primary id
    'targetForeignKey' => 'user_id', //users - primary id
    'joinTable' => 'users_user_groups',
    'through' => 'UsersUserGroups'

Which wouldn’t work since its conditions is WHERE ug_id = instance_id in question

I’m aware that, I can load the users from the controller with

‘contain’ => [‘UserGroups’ => [‘Users’]]

but I want to load Users as a separate array to loop over separately.
Simply wondering if cakephp3 has such functionality? Maybe a through => through???

Not clear what you’re looking for. Just a way to read the entire list of users separate from anything else?

Not the entire list of user, but only list of users related to the instance, I understand that implies having the User Groups containing the users in question,

contain=>[‘UserGroups’ => [‘Users’]]
UserGroups => [
int(0) => {
ug_id = 1
users = [

just was wondering if its possible to get them outside of UserGroups array in the stand alone Users array.

users = [
It’s just I’m migrating and my current templates are prebuilt to loop over single array, and there are a lot of them. Just wanted to know if that’s possible through a setting up associations in a model.