Search code examples
phpcakephpormcakephp-4.x

Always eager load association in CakePHP 4


In my CakePHP 4 project, I have two models with a one-to-many relationship between them:

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

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

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

        // more relations here

        $this->belongsTo('ContentTypes', [
            'className'  => 'ContentTypes',
            'foreignKey' => 'content_type_key',
        ]);
    }
}
<?php

namespace App\Model\Table;

use Cake\ORM\Table;

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

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

        $this->hasMany('Contents',[
            'foreignKey' => 'content_type_key',
        ]);
    }
}

Is there any way that I can assure that the ContentTypes table is always joined to Contents, whenever I query it?

What I would like to achieve is that every time I retrieve a Content entity, the corresponding ContentType entity is also already available.

I stumbled upon the EagerLoader and EagerLoadableclasses while googling, but couldn't find any examples on how to actually use them.


Solution

  • In the end, this was way easier than I originally thought. All I had to do was add a beforeFind method to the ContentsTable class:

        public function beforeFind(EventInterface $event, Query $query)
        {
            $query->contain('ContentTypes');
        }