remove fields from select generated by matching

冷暖自知 提交于 2019-12-12 00:05:54

问题


I have two custom find methods and I would like to make an union of them.

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]);
              }
      );
}

The two methods generates different select list, because of the matching call. So I can not make union of them...

I do not need Groups__id, etc fields to be selected.

Is there any way to tell to matching that it should not add the matching data fields to the created select field list?


回答1:


You have two options"

Select all the fields from the main query

That will make the query builder omit the fields from associations:

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

By specifically selecting the columns you need, you will leave out the columns form associations that can be joined, i.e. the columns from matching.

Use CakePHP 3.1

CakePHP 3.1 introduces a new function called innerJoinWith(), it does exactly the same as matching() but it will not select any columns from the association:

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]);
              }
      );
}


来源:https://stackoverflow.com/questions/31343250/remove-fields-from-select-generated-by-matching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!