[英]Cakephp3: How to search data in paginate with contain condition?
我有兩個表名稱分別是和用戶。 在其他表中有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可以使用普通belongTo
進行處理),我經常使用以下代碼片段:
<?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']);
?>
注釋:我經常使用“全部”作為查找器,因為我也需要列表中的完整記錄...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.