Custom finder selecting fields in associated model Cakephp3

284 Views Asked by At

I have an Event model hasMany Attendances with event_id in the attendances. I want to select some fields in attendance table in my custom find method but the contain() method doesn't join the two tables.

public function findAttendanceDetails(Query $query) 
{
    return $query->contain('Attendances')
                ->select(['Gender' => 'Attendances.gender',
                            'Name' => 'Attendances.full_name'
                            ]);
}

I am getting an error of Error: SQLSTATE[42S22]: Column not found: 1054 Champ 'Attendances.gender' inconnu dans field list and wondering what is missing.

When I use the ->Join() method instead of ->contain(), I get the results.

1

There are 1 best solutions below

0
On

Contain doesn't quite work that way. You would be looking for something like:

return $query->contain(['Attendances']);

Which will just grab and return the full associated table Attendances. Contain looks for an array, not a string value.

If you want specific fields from the associated table, you could try:

return $query->contain(['Attendances' => function ($q) {
    return $q
        ->select(['gender', 'full_name'])
    }
]);

You can read more about using contain here.