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
In the end, this was way easier than I originally thought. All I had to do was add a
beforeFind
method to theContentsTable
class:You could write a custom finder like:
So everytime you need your contents you use this finder.