CakePHP Joining Multiple Instances of the Same Table in Your Model and Controller

Joining the Same Table on Multiple Fields in CakePHP 4

In this example, we want to reference the users for created_by and modified_by fields in our Pos table.  This allows you to reference the different specified users between the created_by and modified_by fields.

Step 1: Create the belongsTo entries in your Models/POsTable.php file, joining created_by and modified_by fields to the Users table, as shown below.  Note, your Definitions will be referenced in the find/pagination within your controller.:

$this->hasOne('CreatedByUser', [
    'className'=>'Users',
    'foreignKey' => 'id',
    'bindingKey' => 'created_by',
    'propertyName' => 'created_by_user',
]);

$this->hasOne('ModifiedByUser', [
    'className'=>'Users',
    'foreignKey' => 'id',
    'bindingKey' => 'modified_by',
    'propertyName' => 'modified_by_user',
]);

 

Step 2: In your controller, add the ClassNames created above, to the "contain" array in your paginate:

$this->paginate = [
    'contain' => ['PoDets', 'CreatedByUser', 'ModifiedByUser'],
    'conditions' => ...

That's it!  Now when you reference the data (e.g. using debug), you will have an array for created_by_user, and modified_by_user, as set in your setName parameter in the table.

Share this Post