CakePHP4中beforeFind用contain()创建重复标题产品时出错
问题原因
你的ProductsTable在beforeFind中全局添加了contain('Photos'),但Muffin/SlugBehavior生成唯一slug时会调用$this->_table->exists($conditions),这个exists()查询也会触发beforeFind钩子,尝试关联Photos。而exists()默认只查询主键字段,关联Photos需要Products表的主键(作为Photos的外键)被正确纳入查询上下文,此时因查询逻辑限制无法加载关联,抛出异常。
解决方法
以下两种方案都能解决问题,按需选择:
方案1:排除exists查询的contain操作
在beforeFind中判断当前查询是否为exists类型,仅在非exists查询时添加关联:
public function beforeFind(EventInterface $event, Query $query, ArrayObject $options, bool $primary) { if (!$query->is('exists')) { $query->contain('Photos'); } return parent::beforeFind($event, $query, $options, $primary); }
方案2:仅在主查询中添加contain
如果你的业务场景只需要在外部主动调用find时自动关联Photos,可通过$primary参数判断:
public function beforeFind(EventInterface $event, Query $query, ArrayObject $options, bool $primary) { if ($primary) { $query->contain('Photos'); } return parent::beforeFind($event, $query, $options, $primary); }
内容的提问来源于stack exchange,提问作者Oliv
相关产品推荐
相关产品推荐

