Retrieve assoicated model with its own assoications through a join table

I have three models: User, Article, and Tag. The associations between them are as follows:

User hasMany Article:

php

$this->hasMany('Articles', [
    'foreignKey' => 'user_id',
]);

Article belongsToMany Tag:

php

$this->belongsToMany('Tags', [
    'foreignKey' => 'article_id',
    'targetForeignKey' => 'tag_id',
    'joinTable' => 'articles_tags',
]);

In the ArticlesController, I am able to successfully include the associated Tag records in the query using the contain method:

php

$query->contain([
    'Tags',
]);

However, when I try to include the associated Tag records through Article in the UsersController, it doesn’t work:

php

$query->contain([
    'Articles' => [
        'Tags',
    ],
]);

I have confirmed that the associations between the models are defined correctly. The issue seems to be related to the belongsToMany association and the joinTable used between Article and Tag.

How can I include the associated Tag records when querying User and access them through the Article association? Is there a specific way to handle nested belongsToMany associations in CakePHP queries?

What does “it doesn’t work” mean? Do you get an error? Just doesn’t load the data you expect?

No error, it just doesn’t contain a tags array when nesting the contains in the users controller. But it does contain a tags array when adding the single contain in the articles controller.

I also see this note in the Sql Log in the DebugKit menu bar when trying to nest contains.

#### Generated Models
The following Table objects used `Cake\ORM\Table` instead of a concrete class:
* ArticlesTags

Oh, I got it working. I didn’t bake the ArticlesTags table. Thanks!

I don’t think you always need that table, unless you’re using the through configuration in your belongsToMany definition?

I don’t think I’m using through, unless it’s a default. All I can say is that it wasn’t working the way I expected it to without that extra table. I just cake/bake all everything without modifications.