Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Unable to contain() same table multiple times using different aliases #17679

Open
@mehov

Description

@mehov

Description

Say I have a join table where I map products to products, for example two counterparts of each other. (Please assume it makes sense.)

Then I want to select a pair of products out of that table. Each product belongsTo category, and finally each category belongsTo store.

In the join table where the product pairs are, I can define the association twice:

    $this->belongsTo('Products', [
        'foreignKey' => 'product_id',
        'joinType' => 'INNER',
    ]);
    $this->belongsTo('RefProducts', [
        'className' => 'Products',
        'foreignKey' => 'ref_product_id',
        'joinType' => 'INNER',
    ]);

But when I find() a product, attempting to contain its counterpart and its own containments, I don't get both sets of contained information. I'm assuming this is because the contained joins use the same aliases. I tried to overwrite the aliases for each individual contain, but it didn't work. My first attempt was the most obvious:

->contain([
    'Categories' => [
        'Stores' => [
        ]
    ],
    'ProductsProducts' => [
        'RefProducts' => [
            'Categories' => [
                'alias' => 'RefCategories',
                'Stores' => [
                    'className' => 'RefStores',
                ]
            ],
        ],
    ],
])

That resulted in The alias association is not defined. I tried a few more and then finally found a complete list of all accepted options:

protected array $_containOptions = [
'associations' => 1,
'foreignKey' => 1,
'conditions' => 1,
'fields' => 1,
'sort' => 1,
'matching' => 1,
'queryBuilder' => 1,
'finder' => 1,
'joinType' => 1,
'strategy' => 1,
'negateMatch' => 1,
];

Unless I'm missing something, there doesn't seem to be a way to manually set an alias for an individual contain?

CakePHP Version

4.4.14

PHP Version

8.3.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions