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

问题描述 投票:0回答:1

标题几乎说明了一切。我有一些带有包含大量数据的字段的表。为了节省性能,我不想默认不选择这些。强调新的默认行为,将问题与其他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'])然后还将选择其他字段,因为selectAllExcept()

select cakephp orm cakephp-3.x
1个回答
0
投票

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

例如,在UsersTable中:

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

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

    return $query;
}

然后在您的控制器中:

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

OR

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

OR

// 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);
© www.soinside.com 2019 - 2024. All rights reserved.