CakePHP 4.4:检索包含与关联匹配的关联的数据

问题描述 投票:0回答:1

我需要一个指示,但无法找到任何相关信息(但也许这是我的错......)。对 CakeBook 也有一个指示就可以了。

在我的申请中,我有

PatientsTable
。一个
Patient
有许多
Notes
,每个
Note
都属于一个
NoteType

所以像这样:

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',
        ]);
    }
}

现在,对于每个

Patient
,我想检索每个
limit(1)
的最后一个(使用
orderDesc('date')
Note
NoteType

如果需要,我还可以进行单独的查询来检索患者 ID。这不是一个问题。 然后,对于每个患者,运行一个新查询(这将使患者的查询总数 + 1,但这对于缓存来说没问题)。

现在我正在尝试检索单个患者的这些数据,只是为了看看它是否有效。 如:

$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();

但它肯定不起作用,以至于我得到的数据对我来说似乎没有意义。

您有什么建议或指示吗?

谢谢你。

cakephp cakephp-4.x
1个回答
0
投票

您想要实现的是一个常见问题,可以通过在患者表中保存一个可空列“last_note_id”来解决

当您保存注释时,请在 NotesTable add 的“afterSave()”回调中添加

public function afterSave($event, $entity, $options) {
    if ($entity->isNew() && $entity->patient_id) {
        $this->Patients->updateAll(['last_note_id' => $entity->id], ['id' => $entity->patient_id]); 
    } 
}

然后添加一个

belongsTo('LastNotes', ['className' => 'Notes'])

始终使用 LastNotes 而不是 Notes 来检索最后一个条目

© www.soinside.com 2019 - 2024. All rights reserved.