1
votes

We are using the new cakePHP ORM and I have some issues understanding the way the new ORM works when dealing with hasMany associations.

E.g. We have a Table called "Users" which has a hasMany relation to another Table "UsersAbsences". The definition and handling itself works fine. We have defined the Table-Objects and the Entities.

$this->addAssociations([
'hasMany' => [
    'UsersAbsences' => [
        'className' => 'UsersAbsences',
        'propertyName' => 'absences',
        'foreignKey' => 'user_id'
    ]
]);

Within our UsersTable we've created a custom method which retrieves details to one User, using the QueryBuilders ->contain Method to fetch the hasMany-associated "UsersAbsences" defined by property "absence". We're setting the view-variable $user to work with the Entity in the template: Works fine.

...
$users->contain(['UsersAbsences',...]);
...

Now the part that puzzles me: The Object-type of $user is "UserEntity". When I now iterate through the $user->absences... i always get CakeEntity objects, not (as I would expect) AbsenceEntity-objects.

Problem: I would like to implement a custom method in the UserAbsence-Entity which I would like to call in the template when iterating through each Absence of the user.

When using the ->contain Method for associations attached with "belongsTo", I get the correct Entity-Class.

Someone an idea how to deal with that?

1

1 Answers

1
votes

Mind your terminology, entity classes do not have a Entity suffix, this makes your question a little confusing, as one might think that you've named all your classes incorrectly! Please use actual, ideally fully qualified classnames in your questions!

That being said, by default the name of the corresponding entity is figured from the table class name, that is, the singular name without Table suffix. So, for UsersTable it's User, and for UsersAbsencesTable it would be UsersAbsence, not just Absence.

So, renaming your Absence entity file/class to UsersAbsence should fix the problem. Alternatively you can manually define the entity class a table should use by specifying it via Table::entityClass().

See also