CakePHP contain is really very helpful when you want to join multiple tables without writing long code. But when we need to do some more complex operation like join the same table multiple time based on the column then we need to update our model. In this tip, I will explain to you how to do that.

Suppose we have a Customer table in which we have two column which stores address table id, the first column is for customer permanent address id and second table store user corresponding address id. Note both address ids come from the Address table.

Now we need to tell CakePHP to load data according to our need so open customer table model and add bellow code inside initialize function.

public function initialize(array $config)
{
       parent::initialize($config);
    
       $this->belongsTo('PermanentAddress', [
            'foreignKey' => 'permanent_address_id',
            'joinType' => 'LEFT',
            'className' => 'Addresses'
        ]);
        $this->belongsTo('CorrespondenceAddress', [
            'foreignKey' => 'correspondence_address_id',
            'joinType' => 'LEFT',
            'className' => 'Addresses'
        ]);
}

In above code, I give a custom name to belong to relation and define the actual model name in className as mention in above code. Now we can use this reference in our content to load data.

$customerAddress = $this->CustomerAddresses->findByCompanyId($companyId)
    ->contain([
        'PermanentAddress',
        'CorrespondenceAddress'
    ])
    ->hydrate(false)
    ->first();

Now you can get your data from database using this technique. Hope this post helps you. Thanks 🙂