1

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": "mynane@yahoo.co.uk",
        "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

ndm
  • 59,784
  • 9
  • 71
  • 110
Yomi Ojo
  • 21
  • 1
  • 3
  • Are there any attributes at all associated? Check the keys in the table. Also check the generated SQL query. If there is no exceptio the bindings are usually correct. Also, why aren't you using the query builder over the old array notation? – floriank Sep 04 '17 at 19:12

0 Answers0