Best practice for accessing additional data (many to many)

Hi folks,

I got a question regarding “joinData” in a belongsToMany (many to many) relation.

Lets assume we have 3 tables
ATable, BTable and ABTable

ABTable contains some additional data for example a price value.

ATable defines $this->belongsToMany(‘B’, [‘through’ => ‘AB’ ]);
BTable defines $this->belongsToMany(‘A’, [‘through’ => ‘AB’ ]);

We also have an own entity class for each table:
A, B and AB.

Now I try this:

Get an A entity
$a = $this->A->get(1, [‘contain’ => [‘B’]])

Than dd($a->b[0]); would return something like this

‘_joinData’ => object(Cake\ORM\Entity) {

‘price’ => (float) 123,
‘[repository]’ => ‘AB’

My question is why I am not getting an instance of “App\Model\Entity\AB” instead of the “_joinData”?
Is this the normal cakephp behaviour for accesing the additional stored data in an many to many table?

Best regards

I don’t think you should have the “Table” at the end of your through key. Try just 'through' => 'AB'.

Thanks you are right. I had it right in my code but did it wrong here in my example. But it still doesnt work.
The “joinData” key is still there and it is not converted into an Entity of AB.

I think this is the normal cake behaviour but is there any way to convert the join data automaticly into the belonging entity?

Just checked mine, and the _joinData is indeed the specific entity type, not a generic one. I’d double-check your file and class naming structure to make sure that everything is as it should be (singular vs plural, in the right namespaces, etc.). You might want to inspect the return values of things like TableRegistry::get('AB'), TableRegistry::get('AB')->newEntity() and new \App\Model\Entity\AB(), those might help you quickly figure out which piece of the puzzle is wrong.

1 Like

Thank you I will try it later :slight_smile:

YOu were right. A single get() to the AB Table does also return a generic Entity. I can set it in ABTable with $this->setEntityClass(’…’); and it works.
And now I also found out that I had the wrong Entity name to make it work out of the box :slight_smile: Thanks for your help!