【问题标题】:Insert data into two tables (foreign key joined) from one form in CakePHP从 CakePHP 中的一个表单将数据插入两个表(外键连接)
【发布时间】:2013-02-14 06:17:17
【问题描述】:

我在 CakePHP 中有一个表格如下 addticket.ctp

    <html>
<?php
    echo $this->Form->create('Ticket', array('url' => array('controller' => 'tickets', 'action' =>'addtickets'),
        'enctype' => 'multipart/form-data'));
    echo $this->Form->input('title',array('label'=>'Title'));
    echo $this->Form->input('attachment', array('between'=>'<br />','type'=>'file',

        'label'=>'Attachment'));
    echo $this->Form->input('stepstoreproduce',array('label'=>'Steps To Reproduce'));
    echo $this->Form->input('category',array(
        'label'=>'Category',
        'options'=>array(
            'IT Support',
            'IT HelpDesk'
            )));
    echo $this->Form->input('priority',array(
        'label'=>'Priority',
        'options'=>array(
            'Low',
            'Medium',
            'High'
            )));
    echo $this->Form->input('Comment.comment',array(
        'type'=>'textarea',
        'label'=>'Comments'
        ));
    echo $form->input('public',array('type'=>'radio',
    'options' => array(
        '1'=>'Yes',
        '0'=>'No',
    ),
    'default'=>'0'));
    echo $form->input('created_by',array('value'=>$_SESSION['Auth']['User']['id'],'type'=>'hidden'));

    echo $this->Form->end('Submit Ticket');

?>
</html>

我有以下代码的模型ticket.php

var $hasMany = array(
    'Comment' => array(
        'className'     => 'Comment',
        'foreignKey'    => 'ticket_id'
        )
);

我有带有 addticket() 函数的tickets_controller,如下所示

 if ($this->Ticket->saveAll($this->data)){
            $this->Session->setFlash('Ticket created');
        } 
        else {
            $this->Session->setFlash('Cannot create a ticket');
        }

问题 问题是我的数据库中有两个表: 1.门票 2.评论(ticket_id为外键)

我想将票据数据插入tickets 表,并将 cmets 数据插入comments 表。据我所知,将名称更改为Comment.comment 将在 cmets 表中插入数据。

但我想在评论表中添加 useridticket_idcreated_by 在门票和 cmets 中。

请帮忙 提前致谢

【问题讨论】:

  • 如果我是你,我不会将隐藏的 user_id 字段设为输入字段...除非您使用安全组件,否则您是在自找麻烦!使用控制器填充它,或者在模型中使用 beforeSave 来操作正在保存的数据。

标签: cakephp cakephp-1.3


【解决方案1】:

我认为您需要在您拥有的每个输入字段前面明确地放置一个模型名称。例如:

echo $this->Form->input('Ticket.title',array('label'=>'Title'));
echo $this->Form->input('Ticket.attachment', array('between'=>'<br />','type'=>'file',

    'label'=>'Attachment'));

CakePHP 会自动在您的评论数据中设置ticket_id。 详情请参阅http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array

而且我认为您应该在控制器中设置 user_id,而不是在如下视图中将其设置为隐藏字段:

$this->data['Ticket']['created_by'] = $this->Auth->user('id');
$this->data['Comment']['created_by'] = $this->Auth->user('id');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多