skip to Main Content

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

<?php

namespace AppModelTable;

use CakeORMTable;

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 AppModelTable;

use CakeORMTable;

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.

2

Answers


  1. Chosen as BEST ANSWER

    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');
        }
    

  2. You could write a custom finder like:

    // in your ContentsTable.php
    public function findWithType(Query $query, array $options):Query{
       return $query->contain(['ContentTypes']);
    }
    
    // somewhere in your application
    $contents = $this->Contents->find('withType');
    

    So everytime you need your contents you use this finder.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search