0

I am trying to find from table "spots" a single instance, with a set of deep associations. Spots have one template, which has multiple "fields", which in turn have multiple "fieldentries". A "fieldentry" however, is also associated with the particular "spot". I hope this makes sense.

My finder looks like this:

public function findFull(Query $query, array $options)
{
    $query->contain([
        'Template' => [
            'Fields' => [
                    'Fieldentry' => function($q){
                        return $q->matching('Spots.id');
                    }
                ]
            ]
    ]);
    return $query;
}

Calling this gives me all "fieldentries" associated with the field. But I need that selection restricted to just the one that is linked to the spot in question.

I am fairly sure that the problem is with the matching function, but I can't figure out how to do that properly. I can make it work by passing the spot id by the options argument, but I would like to be able to do this without knowing the id beforehand (using another finder with different conditions on the spot). So I was hoping for a more "automagic" solution. Is this not possible?

  • Check **https://stackoverflow.com/questions/26799094/how-to-filter-by-conditions-for-associated-models** – ndm Dec 12 '17 at 21:07
  • Thank you, but I don't see how that solves the problem. In all of those examples you end up searching for a specific id, which I need to avoid. Or rather - the id needs to come from whatever spot is selected. Imagine I want to select bunch of spots all with their respective associations. Am I making sense? – Jonas Kvist Jensen Dec 13 '17 at 10:16
  • You don't need to use conditions, they're optional, I just wanted you to see how to match deep associations, and that selecting the other way around might be an option too. Imagine what the final SQL should look like, how would you create such a match given that `Fieldentry` will be retrieved in a separate query? You'll most likely have to do this in two steps. Surely you could also select `Fieldentry` by containing it directly under `Spots`, but this would of course not respect possible conditions that would normally apply on `Fieldentry` via `Fields`, so that might not be applicable. – ndm Dec 15 '17 at 14:59
  • Ok, thank you. I'll do the two-step for now :) – Jonas Kvist Jensen Dec 16 '17 at 09:18

0 Answers0