问题
I have a form in CakePHP as following 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>
And I have model ticket.php with following code
var $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'ticket_id'
)
);
And I have tickets_controller with addticket() function as follows
if ($this->Ticket->saveAll($this->data)){
$this->Session->setFlash('Ticket created');
}
else {
$this->Session->setFlash('Cannot create a ticket');
}
Problem The problem is that there are two tables in my database: 1.tickets 2.Comments (ticket_id is foreign key )
I want to insert tickets data to tickets
table and comments data to comments
table. As I know that changing name to Comment.comment
will insert data in comments table.
But I want to add userid
and ticket_id
in comment table and
created_by
in tickets & comments both.
Please Help Thanks in advance
回答1:
I think you need to explicitly put a Model name in front of every input field you have. For example:
echo $this->Form->input('Ticket.title',array('label'=>'Title'));
echo $this->Form->input('Ticket.attachment', array('between'=>'<br />','type'=>'file',
'label'=>'Attachment'));
CakePHP will automatically set ticket_id in your Comment data. See http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array for more detail.
And I think you should set the user_id in the controller instead of set it as a hidden field in a view like:
$this->data['Ticket']['created_by'] = $this->Auth->user('id');
$this->data['Comment']['created_by'] = $this->Auth->user('id');
来源:https://stackoverflow.com/questions/14868854/insert-data-into-two-tables-foreign-key-joined-from-one-form-in-cakephp