My school model has a many to many
relationship with my attribute model joined by attribute_school
table.
In my Shell folder for cron job i have the following in my main function:
$schoolsRaw = TableRegistry::get('Schools');
$schools = $schoolsRaw->find('all', [
'fields' => [
'Schools.name',
'Schools.logo',
'Schools.discount'
],
'contain' => [
'Users'=> [
'fields' => [
'Users.first_name',
'Users.last_name',
'Users.email',
'Users.title'
]
],
'Attributes' => [
'fields' => [
'Attributes.model'
]
]
]
]);
echo debug(json_encode($schools , JSON_PRETTY_PRINT));
The above echo commands keep generating empty values for all instance of the school record like this:
{
"name": "Genesis School",
"logo": "badges\/genesis.jpg",
"discount": "Not Stated",
"attributes": [],
"user": {
"first_name": "xxxxx",
"last_name": "yyyyy",
"email": "[email protected]",
"title": "Ms"
}
My models:
//schools
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('schools');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsToMany('Attributes', [
'foreignKey' => 'school_id',
'targetForeignKey' => 'attribute_id',
'joinTable' => 'attributes_schools'
]);
}
// attributes model
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('attributes');
$this->setDisplayField('name');
$this->belongsToMany('Schools', [
'foreignKey' => 'attribute_id',
'targetForeignKey' => 'school_id',
'joinTable' => 'attributes_schools'
]);
}
// join table
public function initialize(array $config)
{
parent::initialize($config);
$this->primaryKey('id');
$this->setTable('attributes_schools');
$this->belongsTo('Schools', [
'foreignKey' => 'school_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Attributes', [
'foreignKey' => 'attribute_id',
'joinType' => 'INNER'
]);
}
This is cakephp 3.4 and I don't know why it is not fetching attributes records and no bug is logged. Please help