【问题标题】:Cakephp: Saving the array value not the integerCakephp:保存数组值而不是整数
【发布时间】:2014-01-16 00:31:17
【问题描述】:

过滤一些数据后,我创建了一个变量$customers。这个变量是一个简单的数组 具有以下值:

    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', 'Customer2', 'Customer3'

到目前为止,Eveyting 工作正常。

现在,在用户提交数据后,我想在控制器中做一些进一步的逻辑。我想获取用户选择的数据并将其保存在第二个表中。所以我这样做:

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

数据保存在第二个表中,但问题是保存值 '1', '2', '3' 而不是客户的姓名。如何保存客户的姓名而不是数组中的标识符号。

请多多包涵,我是 cakephp 和一般 php 的新手。

【问题讨论】:

    标签: php cakephp cakephp-2.0 cakephp-model


    【解决方案1】:

    我认为这实际上是您的 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-&gt;request-&gt;data['Invoice']['customer_id'] 等于 1、2 或 3 等。

    我的建议是从问题的根源解决这个问题,我认为通过只将值传递到您的选择框中,您应该得到这样的 HTML:

    <option>Customer1</option>
    

    ...这意味着$this-&gt;request-&gt;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 查找名称。

    您可能只想通过将客户姓名存储为文本来执行此操作的一个可能原因是您希望存储客户姓名按当时的显示方式,这意味着如果它在将来,以前附有该名称的发票不会随之更改,因为该名称存储在文本中,而不是对包含更改的名称的另一个表的数字引用。

    希望这会有所帮助。

    文档

    【讨论】:

    • 非常感谢@scrowler。你的解释很好,关于加入表格的建议是正确的:) 今天你是我的英雄
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多