在CakePHP 3.2中从数据库中提取时,如何在查询中添加条件。 在这里,我实现了一个分页,很容易通过WHERE条件(参见下面的代码)。
public $paginate = [
'fields' => ['Users.id', 'Users.email', 'Users.name', 'Users.is_active'],
'limit' => 1,
'conditions'=>['Users.is_active' =>1],
'order' => [
'Users.id' => 'asc'
]
];
public function index() {
$users = $this->paginate($this->Users);
$this->set(compact('users'));
}
在上面的代码中,我使用了分页,因此我很容易传递条件和其他内容,如字段,顺序等。
如果没有分页,那么代码是什么?在这里,我只需要从数据库中获取数据,然后给出条件和其他东西。 在CakePHP 2.6中,代码如下所示。
$this->EventCategory->find('all', array('conditions' => array('EventCategory.is_active' => 1), 'fields' => array('EventCategory.id', 'EventCategory.name')));
在CakePHP 3.2中,有没有其他方法可以像上面那样(没有分页)?
欢迎提出任何建议。提前谢谢。
答案 0 :(得分:2)
请阅读文档http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html
$query = $this->EventCategory->find('all')
->select(['EventCategory.id', 'EventCategory.name'])
->where(['EventCategory.is_active' => 1]);
答案 1 :(得分:0)
在控制器中使用此代码
$con=[];
$con['Users.role_id'] = 3;
if (isset($this->request->query['keyword']) && !empty($this->request->query['keyword'])) {
$keyword = trim($this->request->query['keyword']);
$con['OR'] = ['Users.phone LIKE' => '%' . $keyword . '%', 'Users.name LIKE' => '%' . $keyword . '%', 'ContractorDetails.company_name LIKE' => '%' . $keyword . '%', 'ProjectTypes.name LIKE' => '%' . $keyword . '%'];
}
$this->paginate = [
'sortWhitelist' => ['ContractorDetails.company_name', 'ProjectTypes.name', 'Users.name', 'Users.id', 'Users.phone', 'Users.deleted', 'Users.probationary'],
'contain' => ['ContractorDetails.ProjectTypes'],
'conditions' => $con,
'order' => ['Users.id' => 'desc'],
'limit' => (isset($this->request->query['limit'])) ? $this->request->query : 10,
];
$users = $this->paginate($this->Users);
$this->set(compact('users'));
在view.ctp
中使用此权限use Cake\Core\Configure;
use Cake\I18n\Number;
<div class="row">
<div class="col-sm-6">
<div class="dataTables_info" id="editable_info" role="status" aria-live="polite"><?= $this->Paginator->counter(['format' => 'Showing {{start}} to {{end}} of {{count}} contractors']) ?></div>
</div>
<?php if ($this->Paginator->counter(['format' => '{{pages}}']) > 1) { ?>
<div class="col-sm-6">
<div class="dataTables_paginate paging_bootstrap" id="editable_paginate">
<ul class="pagination pull-right">
<?= $this->Paginator->prev('Previous') ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next('Next') ?>
</ul>
</div>
</div>
<?php } ?>
</div>