0

I need an indication, having not been able to find anything about it (but maybe it's my fault...). An indication also to the CakeBook will be fine.

In my application I have the PatientsTable. A Patient has many Notes and each Note belongs to a NoteType.

So something like this:

class PatientsTable extends AppTable
{
    public function initialize(array $config): void
    {
        // ...

        $this->hasMany('Notes', [
            'foreignKey' => 'patient_id',
        ]);
    }
}
class NotesTable extends AppTable
{
    public function initialize(array $config): void
    {
        // ...

        $this->belongsTo('NotesTypes', [
            'foreignKey' => 'notes_type_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Patients', [
            'foreignKey' => 'patient_id',
            'joinType' => 'INNER',
        ]);
    }
class NotesTypesTable extends AppTable
{
    public function initialize(array $config): void
    {
        // ...

        $this->hasMany('Notes', [
            'foreignKey' => 'notes_type_id',
        ]);
    }
}

Now, for each Patient, I would like to retrieve the last (using limit(1) and orderDesc('date')) Note for each NoteType.

I can also do a separate query to retrieve patient IDs if that is needed. It's not a problem. And then, for each patient, run a new query (this would bring the total of queries to patients + 1, but that's fine with caching).

Right now I'm trying to retrieve this data for a single patient, just to see if it works. As:

$noteTypes = $this->Notes->NotesTypes->find()
    ->contain('Notes', function (Query $Query): Query {
        return $Query
            ->matching('Patients', function (Query $Query): Query {
                return $Query->where(['Patients.id' => 35]);
            })
            ->orderDesc('date')
            ->limit(1);
    })
    ->all();

But it certainly doesn't work, so much so that the data I get like this doesn't even seem to make sense to me.

Do you have any suggestions or indications?

Thank you.

Mirko Pagliai
  • 1,220
  • 1
  • 19
  • 36
  • https://stackoverflow.com/questions/30241975/how-to-limit-contained-associations-per-record-group might help? You could use something there to load patients, containing notes limited to one per type. – Greg Schmidt Aug 24 '23 at 21:04
  • Thanks @GregSchmidt so this another duplicated of https://stackoverflow.com/questions/29775766/using-limit-on-contained-model because seems the problem is the `limit` – Mirko Pagliai Aug 25 '23 at 07:06

0 Answers0