我想在Cake
PHP 3.0中的
virtual field/entity property上创建一个
pagination sort link.
在CakePHP 2.x中,我曾经创建了一个virtual field,然后在该字段上创建了一个分页排序链接.但是,在CakePHP 3.0中,virtual fields已被virtual entity properties取代.
在我的情况下,我有一个first_name和last_name列,它们在virtual entity property中组合为full_name.我想对full_name进行排序.
如链接文档中所述,虚拟属性不能用于查找.这是设计的,虚拟属性只存在于实体中,它们是在从数据库中检索数据后用PHP构建的.
原文链接:https://www.f2er.com/php/135573.html需要通过sortWhitelist指定计算列
就像关联模型的列一样,需要在sortWhitelist选项中指定计算列,以便可用于排序!
Cookbook > Controllers > Components > Pagination > Control which Fields Used for Ordering
通过分页选项
这里有一些选项,例如您可以在分页选项中定义计算列:
$this->paginate = [ // ... 'sortWhitelist' => [ 'id','first_name','last_name','full_name',// ... ],'fields' => [ 'id','full_name' => $this->Table->query()->func()->concat([ 'first_name' => 'literal','last_name' => 'literal' ]),'order' => [ 'full_name' => 'DESC' ] ];
定制查找器
另一个更可重复使用的选项是使用自定义查找程序:
$this->paginate = [ // ... 'sortWhitelist' => [ 'id','finder' => 'withFullName','order' => [ 'full_name' => 'DESC' ] ];
public function findWithFullName(\Cake\ORM\Query $query,array $options) { return $query->select([ 'id','full_name' => $query->func()->concat([ 'first_name' => 'literal',// ... ]); }
> Cookbook > Controllers > Components > Pagination > Using Controller::paginate()
> Cookbook > … ORM > Retrieving Data & Results Sets > Custom Finder Methods
也可以直接将查询对象传递给Controller :: paginate():
$this->paginate = [ // ... 'sortWhitelist' => [ 'id','order' => [ 'full_name' => 'DESC' ] ]; $query = $this->Table ->find() ->select(function (\Cake\ORM\Query $query) { return [ 'id','full_name' => $query->func()->concat([ 'first_name' => 'literal','last_name' => 'literal' ]),// ... ]; }); $results = $this->paginate($query);