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

gfttwv5a  于 2023-10-20  发布在  PHP
关注(0)|答案(1)|浏览(149)

我需要一个指示,没有能够找到任何关于它(但也许这是我的错.)。一个指示也到蛋糕书将是罚款。
在我的应用程序中,我有PatientsTable。一个Patient有许多个Notes,每个Note属于一个NoteType
比如说

  1. class PatientsTable extends AppTable
  2. {
  3. public function initialize(array $config): void
  4. {
  5. // ...
  6. $this->hasMany('Notes', [
  7. 'foreignKey' => 'patient_id',
  8. ]);
  9. }
  10. }
  1. class NotesTable extends AppTable
  2. {
  3. public function initialize(array $config): void
  4. {
  5. // ...
  6. $this->belongsTo('NotesTypes', [
  7. 'foreignKey' => 'notes_type_id',
  8. 'joinType' => 'INNER',
  9. ]);
  10. $this->belongsTo('Patients', [
  11. 'foreignKey' => 'patient_id',
  12. 'joinType' => 'INNER',
  13. ]);
  14. }
  1. class NotesTypesTable extends AppTable
  2. {
  3. public function initialize(array $config): void
  4. {
  5. // ...
  6. $this->hasMany('Notes', [
  7. 'foreignKey' => 'notes_type_id',
  8. ]);
  9. }
  10. }

现在,对于每个Patient,我想检索每个NoteType的最后一个(使用limit(1)orderDesc('date')Note
如果需要,我还可以执行单独的查询来检索患者ID。这不是问题然后,对每个患者运行一个新的查询(这将使查询总数为patients + 1,但这对缓存来说很好)。
现在我正试图检索单个患者的数据,只是想看看它是否有效。如:

  1. $noteTypes = $this->Notes->NotesTypes->find()
  2. ->contain('Notes', function (Query $Query): Query {
  3. return $Query
  4. ->matching('Patients', function (Query $Query): Query {
  5. return $Query->where(['Patients.id' => 35]);
  6. })
  7. ->orderDesc('date')
  8. ->limit(1);
  9. })
  10. ->all();

但它肯定不起作用,以至于我这样得到的数据对我来说甚至没有意义。
你有什么建议或指示吗?
谢谢

6kkfgxo0

6kkfgxo01#

您试图实现的是一个常见问题,可以通过在患者表中保存**可空列“last_note_id”**来解决
当你在NotesTable add的“afterSave()”回调中保存一个注解时,

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

然后添加一个

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

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

相关问题