1

I'm looking for the way to do an equivalent to cakephp2's 'recursive' => -1 on a find().

I have a Model Categories that uses the TreeBehavior.

In my controller I get the path of the category :

// in CategoriesController.php
$path = $this->Categories->find('path', ['for' => $id]);

But I have the error message Unable to load Photos association. Ensure foreign key in Categories is selected

The problem is that find('path') above seems to try to find as well associated Model to Categories as Categories uses another behavior (AttachmentBehavior) that adds contain('Photos') :

// in AttachmentBehavior (that is used by `CategoriesTable`)
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
    $query->contain('Photos');

    return $query;
}

How can I remove contain() in $this->Categories->find('path', ['for' => $id]). Is there an option ?

I tried $this->Categories->find('path', ['for' => $id, 'contain' => []) but I have the same error...

Oliv
  • 236
  • 3
  • 12
  • Detach that behavior before making this particular call? But why is Categories even using the AttachmentBehavior if there is no association to Photos? – Greg Schmidt Jan 05 '22 at 20:07
  • @GregSchmidt `Categories` do have association to `Photos`. When I do `$category = $this->Categories->findById($id)->first()` the category contains `Photos` because of `AttachmentBehavior::beforeFind()`. The error is when I do `$path = $this->Categories->find('path', ['for' => $id])`. How would you suggest to detach behavior before making this call ? – Oliv Jan 05 '22 at 20:27
  • With the [`removeBehavior`](https://book.cakephp.org/4/en/orm/behaviors.html#removing-loaded-behaviors) call. – Greg Schmidt Jan 06 '22 at 00:55
  • @GregSchmidt I find strange to have to remove the behavior from the controller, just before the line `$path = $this->Categories->find('path', ['for' => $id])`. It's not looking clean to me. – Oliv Jan 06 '22 at 18:33
  • Well, it seems you have a behavior that needs to be attached to that table sometimes, but not always. So you can add it in the general case and remove it when not needed. Or you can add it only when required. Or you can change the implementation of the behavior, if it's something under your control. If the latter, you could pass some specific option in the `find` call that tells the behavior not to bother. But that feels worse to me, having a behavior that can be told not to do the one thing that it's there for. – Greg Schmidt Jan 06 '22 at 19:06

0 Answers0