我有两个表名称分别是和用户。在其他表中有driver_id和vendor_id。用户表中的两个ID均带有名称ID列。这是我的示例代码。
src /模型/表格/Miscellaneous.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class MiscellaneousTable extends Table {
public function initialize(array $config) {
$this->table('miscellaneous');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Vendors', [
'foreignKey' => 'vendor_id',
'className' => 'users',
'joinType' => 'left'
]);
$this->belongsTo('Drivers', [
'foreignKey' => 'driver_id',
'className' => 'users',
'joinType' => 'left'
]);
}
}
我想搜索供应商名称和驱动程序名称。这是我的分娩条件:
if (!empty($this->request->data['vendor']['name'])) {
$vendor_name = $this->request->data['vendor']['name'];
}
if (!empty($this->request->data['driver']['name'])) {
$driver_name = $this->request->data['driver']['name'];
}
$miscellaneous = $this->paginate($this->Miscellaneous, ['contain' => ['Drivers' => function(\Cake\ORM\Query $q) {
return $q->where(['Drivers.name LIKE ' => '%'.$driver_name.'%']);
}, 'Vendors' => function(\Cake\ORM\Query $q) {
return $q->where(['Vendors.name LIKE ' => '%'.$vendor_name.'%']);
}], 'conditions' => $con, 'order' => ['Miscellaneous.id' => 'DESC']]);
但是它什么也没显示。请帮助我找到正确的解决方案。
它的工作不受供应商和驱动程序名称的限制。
最佳答案
对于belongTo
关联(Cake可以使用普通Joins处理),我经常使用以下代码片段:
<?PHP
$whereArray = [];
if (!empty($this->request->data['vendor']['name'])) {
$whereArray[] = ['Vendors.name LIKE ' => '%'.$this->request->data['vendor']['name'].'%'];
}
if (!empty($this->request->data['driver']['name'])) {
$whereArray[] = ['Drivers.name LIKE ' => '%'.$this->request->data['driver']['name'].'%'];
}
$miscellaneous = $this->paginate($this->Miscellaneous->find('all', ['contain' => ['Vendors', 'Drivers']])->where($whereArray)->order(['Miscellaneous.id' => 'DESC']);
?>
注释:我经常使用“全部”作为查找器,因为我也需要列表中的完整记录...
关于php - Cakephp3:如何搜索包含条件的分页数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53681422/