Eager loading after insert in CakePHP 4

Viewed 29

Let's say I have two tables: Users

<?php

namespace UserManager\Model\Table;

use Cake\ORM\Table;

class UsersTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setPrimaryKey('id');

        $this->belongsTo('Groups', [
            'className' => 'UserManager.Groups',
            'foreignKey' => 'group_id',
        ]);
    }

    public function afterSave(EventInterface $event, User $entity)
    {
        /*
        $entity->group here is NULL
        but $entity->group_id contains the correct value

        I need the group to do some additional user permissions logic here
        */
    }
}

and Groups:

<?php

namespace UserManager\Model\Table;

use Cake\ORM\Table;

class GroupsTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('groups');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->hasMany('Users', [
            'className' => 'UserManager.Users',
            'foreignKey' => 'group_id',
        ]);
    }
}

that are linked to each other by a belongsTo/hasMany relation.

And in my controller, I have the function to save a new user:

<?php

namespace UserManager\Controller\Admin;

use App\Controller\AppController;

class UsersController extends AppController
{
    public function add()
    {
        $user = $this->Users->newEmptyEntity();
        if ($this->getRequest()->is('POST')) {
            $user = $this->Users->patchEntity($user, $this->getRequest()->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }
    }
}

The group id is a required filed in the form, and in fact, in the afterSave method $entity->group_id contains the correct numeric value that I expect.

Is there any way that, in the afterSave method, I can do $entity->group to access the Group entity that is linked to my User entity? Can I add a contain option to the save()?

Or am I out of luck, and I do need to explicitly load the Group entity with a query?

Of course I can simply do

$groupsTable = TableRegistry::getTableLocator()->get('UserManager.Groups');
$group = $groupsTable->get($entity->group_id);

in the afterSave method, but I was wondering if there was a more "elegant" way.

0 Answers
Related