1
我在處理獲取基於不同但相關表上的搜索條件的項目列表時遇到了一個持續性問題。我需要清楚如何處理這種情況。這是我最簡單的例子:使用相關模型的cakephp搜索條件
如果我有一個代理模型(使用名爲r_num的主鍵和代理模型的表使用名爲代理的表,代理表包含r_num的外鍵鏈接到機構,該機構可以有許多代理人:
表:轉診
r_num int -- primary key auto incremented
r_company varchar(50) -- the name of the agency
... other fields don't matter
表:代理
a_num int -- primary key auto incremented
r_num int -- foreign key to the referral table
a_lname varchar(50) -- agent's last name
a_fname varchar(50) -- agent's first name
a_email varchar(50) -- agent's email
型號:
class Agency extends AppModel {
var $name = 'Agency';
var $useTable = 'referral';
var $primaryKey = 'r_num';
var $hasMany = array(
'Agent' => array(
'className' => 'Agent',
'foreignKey' => 'r_num',
'order' => 'Agent.a_lname DESC',
'dependent'=> true
)
);
}
class Agent extends AppModel {
var $name = 'Agent';
var $primaryKey = 'a_num';
}
所有我想要的是返回使用$這個 - >列表Agency->找到(「全部」)使用條件,從搜索的形式,其中包括代理第一名稱,代理姓氏,代理人電子郵件。我需要一份代理公司名稱和ID列表,但搜索標準是基於代理商的。我有幾種不同的模型可以使用它,所以我需要文檔說明如何工作。基於我在網上找到的是我在網上找到的這個是在AgencyController中工作,但它是一種黑客,它不會在我的一些更復雜的情況下工作:我需要這樣做,而無需進行多次調用,因爲一些的表格會返回大量的行,並且在這些查詢中使用這種技術需要幾分鐘的時間。
class AgenciesController extends AppController {
var $helpers = array ('Html','Javascript', 'Form', 'Paginator', 'Ajax', 'Phoneformat');
var $name = 'Agencies';
var $components = array('RequestHandler', 'RentalValidation');
var $uses = array('Agency', 'Agent');
function index() {
$criteria = $this->postConditions($this->data);
if (empty($criteria)){
$arrArgs = $this->passedArgs;
unset($arrArgs['page']);
$criteria = $arrArgs;
}
$searchcriteria = array();
foreach (array('Agency.r_state', 'Agency.r_company') as $item) {
$itemvalue = '';
if (isset($criteria[$item])){
$itemvalue = $criteria[ $item];
if (!empty($itemvalue)) {
$searchcriteria[$item . " LIKE "] = '%' . $itemvalue .'%';
}
}
}
foreach (array('Agent.a_lname', 'Agent.a_email') as $item) {
$itemvalue = '';
if (isset($criteria[$item])){
$itemvalue = $criteria[ $item];
if (!empty($itemvalue)) {
$agent_rnums = $this->Agent->find('list',
array('conditions' =>
array($item . " LIKE " => '%'. $itemvalue .'%'),
'fields' => 'Agent.r_num'));
$searchcriteria['r_num'] = $agent_rnums;
}
}
}
$this->set('passedCriteria', $criteria);
$data = $this->paginate('Agency', $searchcriteria);
if (count($data) == 1) {
$referralid = $data[0]['Agency']['id'];
$this->redirect(array('action' => 'edit', $referralid));
}
$this->set('agencies', $data);
}
}
這就是上面的代碼現在所做的。 $ agent_rnums是與條件匹配的代理,然後我將該數組添加到自動轉換爲IN的搜索條件,因此它執行2個SQL調用。有一種叫deepfind的東西,應該把這些東西結合起來,讓它更有效率,我還沒有能夠讓它工作。 – stephenbayer 2011-02-18 15:52:08