CakePHP 3 - 除非特别选择,否则在查询中默认排除字段

CakePHP 3 - Exclude fields by default in query unless specifically selected

标题几乎说明了一切。我有一些包含大量数据的字段的表。为了节省一些性能,我不想默认 SELECT 这些。
强调新的默认行为,将问题与例如Select all except one field in cakephp 3 query

示例:

$cities = $this->Cities->find();

// A $city does not include the field `shape` (which is a huge polygon)
$cities = $this->Cities->find(['id', 'name', 'shape']);

// A $city now does include the `shape` property

我查看了实体的 accessiblehidden 属性,但这些似乎不会影响 SELECT 语句。

编辑:selectAllExcept 查询似乎很有用。我将它与 beforeFilter 事件结合起来,如下所示:

public function beforeFind($event, $query, $options, $primary)
{
    $query->selectAllExcept($this, ['shape']);
}

这适用于空查询,shape 现在已被排除。但是现在我无法控制可能要包含或不包含的其他字段:
$this->Cities->find()->select(['id', 'shape']) 也会 select 其他字段,因为 selectAllExcept().

您可以简单地覆盖 table 中的 find('all') 方法。

例如在 UsersTable 中:

public function findAll(Query $query, array $options)
{

    $query->selectAllExcept($this, ['password']);

    return $query;
}

然后在你的控制器中:

// select all except password
$users = $this->Users->find();
debug($users);

// we try to select some fields, without success
$users = $this->Users->find()->select(['id', 'username', 'password']); 
debug($users);

// we try to select some fields incl. password, with success
$users = $this->Users->find()->select(['id', 'username', 'password'], true); // <-- this overwrite select / selectAllExcept in custom finder
debug($users);