2014-01-16 35 views
1

過濾了一些數據後,我創建了一個變量$ customers。這個變量是一個簡單的數組 ,其具有下面的值:Cakephp:保存數組值不是整數

array(
     (int) 1 => 'Customer1', 
     (int) 2 => 'Customer2', 
     (int) 3 => 'Customer3' 
    ) 

我通過從控制器此數組這樣

$this->set('customers', $customers); 

在我的形式使用該陣列,使得該視圖的視圖用戶可以選擇一個

echo $this->Form->input('customer_id', array('options' => array($customers))); 

其上顯示在選擇表格中的數據是本「customer1表」,「顧客2」,「Customer3'

Eveyting迄今爲止工作正常。

現在,在用戶提交數據後,我想在控制器中做一些更進一步的邏輯。我想獲取用戶選擇的數據並將其保存在第二個表中。所以我這樣做:

$this->Invoice->set('secondtabel', $this->request->data['Invoice']['customer_id']); 

的數據被保存在第二個表,但問題是保存價值「1」,「2」,「3」不是客戶的名字。我如何保存客戶的名稱而不是數組中的標識符號碼。

請耐心等待,我是cakephp和php的新手。

回答

2

我認爲這實際上是與你的HTML一個問題,您的選擇框可能看起來是這樣的:

<select name="customer_id"> 
    <option value="1">Customer1</option> 
    <option value="2">Customer2</option> 
    <option value="3">Customer3</option> 
</select> 

這就是爲什麼你的價值是1,2或3,而不是customer1表等,因爲$this->request->data['Invoice']['customer_id']是等於1,2或3等

我的建議是解決這個問題的根源,我認爲通過只傳遞值到您的選擇框,你應該得到這樣的HTML:

<option>Customer1</option> 

...這將意味着$this->request->data['Invoice']['customer_id']將等於Customer1

所以,試試這個:(array_values返回數組只包含值,基本上剝離鍵)

$this->set('customers', array_values($customers)); 

這應該可以解決您的問題。但是,就結構化數據而言,您目前正在執行的方式(存儲1,2或3等)實際上是正確的方式。通過這種方式,您只需加入您檢索這個數據的客戶表,你可以抓住的名字呀......事情是這樣的:

$invoices = $this->Invoice->find('all', array(
    'conditions' => array(
     // your custom find conditions 
    ), 
    'joins' => array(
     array(
      'table' => 'customers', 
      'alias' => 'Customer', 
      'type' => 'LEFT', 
      'conditions' => array('Customer.id = Invoice.customer_id') 
     ) 
    ), 
    'fields' => array(
     'Invoice.*', // retrieve regular invoice data 
     'Customer.name' // retrieve the joined customer name too 
    ) 
)); 

這樣你仍然保存客戶ID爲整數,當您去檢索數據時,只需用SQL查找名稱即可。

一個可能的原因,你可能想簡單地通過存儲客戶的名稱作爲文本做到這一點是要存儲,因爲它出現的時候客戶名稱,如果在未來的變化,以前的發票意思與該名稱附加將不會更改,因爲該名稱存儲在文本中而不是數字引用另一個表中包含名稱已更改。

希望這會有所幫助。

文檔

+0

感謝很多@scrowler。你的解釋非常好,關於加入表格的建議是正確的:)今天你是我的英雄 – RaduS