src/Controller/LeadsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
class LeadsController extends AppController {
public function initialize() {
parent::initialize();
// $this->viewBuilder()->setLayout("default");
$this->loadModel('Leads');
}
public function index() {
$result = $this->Leads->find()->contain(['Openers', 'Closers']);
foreach ($result as $lead) {
pr($lead);
}
}
}
src/Model/Table/LeadsTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class LeadsTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Openers', [
'className' => 'Users',
'foreignKey' => 'lead_id',
'bindingKey' => 'user_id',
'through' => 'LeadsUsers',
])
->setConditions(['LeadsUsers.user_type' => 'Opener'])
->setProperty('openers');
$this->belongsToMany('Closers', [
'className' => 'Users',
'foreignKey' => 'lead_id',
'bindingKey' => 'user_id',
'through' => 'LeadsUsers',
])
->setConditions(['LeadsUsers.user_type' => 'Closer'])
->setProperty('closers');
}
}
src/Model/Table/UsersTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Leads', [
'foreignKey' => 'user_id',
'bindingKey' => 'lead_id',
]);
}
}
It’s a many-to-many relationship between Leads and Users. I have created leads_users table in the database, but I do not have the src/Model/Table/LeadsUsersTable.php file.
With the above setup, I get openers and closers arrays in the result, but those are blank.
Thank you.