phpslugcakephp-4.x

contain() in beforeFind() sometimes causes issue in Cakephp4


I have the following association : ProductsTable hasMany PhotosTable.

Furthermore, ProductsTable uses Muffin/SlugBehavior to build a unique slug.

I need to automatically get Photos linked to Products each time I get a Product.

So I use contain() in ProductsTable::beforeFind() because I want it to be independent of any Controller.

Here is my ProductsTable :

// ProductsTable
class ProductsTable extends Table
{
   public function initialize(array $config): void
   {
      $this->hasMany('Photos');

      $this->addBehavior('Muffin/Slug.Slug', [
         'displayField' => 'title', // 'title' is the field I want to build a unique slug from.
      ]);
   }

   public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
   {
      $query->contain('Photos');
      return $query;
   }
}


In most cases it works well, but an issue happens when I try to create a Product with an already existing title (i.e with a slug that already exists).

I have the following InvalidArgumentException : Unable to load Photos association. Ensure foreign key in Products is selected. The exception is thrown in Muffin/SlugBehavior::_uniqueSlug() at the line $this->_table->exists($conditions).

I don't understand exactly what's the problem...

Could anybody tell me how to fix it ?

enter image description here


Solution

  • I've fixed the issue using $query->enableAutoFields() in beforeFind().