【问题标题】:How to find entities with common parent using matching() in CakePHP?如何在 CakePHP 中使用 match() 查找具有共同父对象的实体?
【发布时间】:2016-06-11 15:47:35
【问题描述】:

我需要找到与给定文章列表具有相同作者的所有文章

这是我的自定义查找器方法:

public function findSimilar(Query $query, array $options)
    {
        if (empty($options['idList'])) {
            throw new Exception('idList is not populated');
        }
        // We are given a list of article IDs
        $idList = $options['idList'];

        return $query->matching('Authors', function ($q) use ($idList) {
            return $q->matching('Articles', function ($q2) use ($idList) {
                return $q2->where(['Articles.id IN' => $idList]);
            });
        });
    }

不幸的是,我收到以下错误消息: PDO异常:SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'Articles' 我做错了什么?

【问题讨论】:

    标签: php cakephp cakephp-3.x cakephp-3.2


    【解决方案1】:

    嵌套匹配有很多限制,这可能就是其中之一。我不知道这是否是一个错误,因此您可能需要检查issues on GitHub 并最终提交一个新的以进行澄清。

    引用自文档:

    [...] 点匹配路径应该用于嵌套的matching() 调用[...]

    Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Filtering by Associated Data

    在任何一种情况下,使用点表示法而不是嵌套应该可以解决问题,即

    return $query->matching('Authors.Articles', function ($q) use ($idList) {
        return $q->where(['Articles.id IN' => $idList]);
    });
    

    如果你还想匹配Authors,你可以堆叠匹配器,比如

    return $query
        ->matching('Authors', function ($q) {
            return $q->where(['Authors.foo' => 'bar']);
        })
        ->matching('Authors.Articles', function ($q) use ($idList) {
            return $q->where(['Articles.id IN' => $idList]);
        });
    

    【讨论】:

      【解决方案2】:

      如果它是一个 HasMany 关系,我们可以很容易地做到这一点:

      return $query->where([
         'Articles.author_id IN' => $this->find()
              ->select(['Articles.author_id'])
              ->where(['Articles.id IN' => $idList])
      ]);
      

      // 感谢 CakePHP IRC 频道的 jose_zap

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-15
        • 2014-08-12
        • 1970-01-01
        • 2016-11-28
        相关资源
        最近更新 更多