从匹配生成的 select 中删除字段

remove fields from select generated by matching

我有两个自定义查找方法,我想将它们结合起来。

public function findInGroup(Query $query, array $options)
{
    return $query
      ->matching(
          'Groups',
          function ($q) {
                  return $q->where(['Groups.id' => 1]);
              }
      );
}

public function findAsUser(Query $query, array $options)
{
    return $query
      ->matching(
          'Users',
          function ($q) {
                  return $q->where(['Users.id' => 1]);
              }
      );
}

这两种方法生成不同的 select 列表,因为 matching 调用。所以我无法将它们合并...

我不需要 Groups__id 等字段 selected。

有什么方法可以告诉 matching 它不应该将匹配的数据字段添加到创建的 select 字段列表中吗?

你有两个选择

Select 来自主查询的所有字段

这将使查询构建器忽略关联中的字段:

$query
    ->find('iGroup', $options)
    ->find('asUser', $options)
    ->select($table->schema()->columns());

通过明确 select 您需要的列,您将省去可以连接的列形式关联,即来自匹配的列。

使用 CakePHP 3.1

CakePHP 3.1 引入了一个名为 innerJoinWith() 的新函数,它与 matching() 完全相同,但它不会 select 关联中的任何列:

public function findInGroup(Query $query, array $options)
{
    return $query
      ->innerJoinWith(
          'Groups',
          function ($q) {
                  return $q->where(['Groups.id' => 1]);
              }
      );
}

public function findAsUser(Query $query, array $options)
{
    return $query
      ->innerJoinWith(
          'Users',
          function ($q) {
                  return $q->where(['Users.id' => 1]);
              }
      );
}