【发布时间】:2014-10-27 15:25:17
【问题描述】:
我在 Cake 有一个简单的表格:
我想保存用户和公司表中的信息。
用户表:
公司表:
我需要两个 sql 查询。
首先: - 使用将在公司表中创建的新公司 ID 插入新用户。
以这个案例为例,testza,
用户:(新条目) testza 密码公司 ID(如果是新公司条目,则为新的)
公司(新条目): Id (3) Creaz (name) 500 000 (revenue_generated)。
我想我很清楚:
公司/注册(查看)
<div class="page-header">
<h1>Company Registration</h1>
</div>
<?php echo $this->Form->create('Company'); ?>
<?php echo $this->Form->input('User.username',array('label'=>'Login')); ?>
<?php echo $this->Form->input('User.password',array('label'=>'Password')); ?>
<?php echo $this->Form->input('User.passwordconfirm',array('label'=>'Confirm password','type'=>'password')); ?>
<hr>
<?php echo $this->Form->input('Company.company_id',
array(
'label'=>'Company',
'options' => $companies,
'empty' => 'Select Company Name'
));
?>
<?php echo $this->Form->input('Company.revenue_generated',array('label'=>'Revenue Generated')); ?>
<?php echo $this->Form->end('Envoyer'); ?>
Controller CompaniesController 的操作注册
<?php
class CompaniesController extends AppController{
public $uses = array('User');
public function signup() {
$this->loadModel('Company');
$companies = $this->Company->find('list'); //we get the authors from the database
$this->set('companies', $companies);
if($this->request->is('post') || $this->request->is('put') ){
$d = $this->request->data['User'];
$c = $this->request->data['Company'];
if($d['password'] != $d['passwordconfirm']){
$this->Session->setFlash("Les mots de passes ne correspondent pas","notif",array('type'=>'error'));
}
else{
if(empty($d['password']))
unset($d['password']);
if($this->User->save($d) || $this->Company->save($c)){
$this->Session->setFlash("L'utilisateur a bien été enregistré","notif");
}
}
}
}
..............
用户模型:
<?php
class User extends AppModel{
public $actsAs = array('Containable');
public $belongsTo = array(
'Town' => array(
'className' => 'Town'
),
'Company' => array(
'className' => 'Company'
)
);
public $recursive = -1;
public $order = 'User.id DESC';
public $validate = array(
'username' => array(
'rule' => 'isUnique',
'allowEmpty' => false,
'message' => "Ce nom d'utilisateur est déja pris"
),
'password' => array(
'rule' => 'notEmpty',
'message' => "Vous ne pouvez pas entrer de mot de pase"
)
);
public function beforeSave($options = array()){
if(!empty($this->data['User']['password'])){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
公司模式:
<?php
class Company extends AppModel{
public $validate = array(
'revenue_generated' => array(
'rule' =>'notEmpty',
'message' => 'Enter Your Generated Revenue.',
'required' => true
)
);
}
【问题讨论】:
-
你正在使用 ($this->User->save($d) || $this->Company->save($c)) 我猜它不起作用,你需要让 company_id 将其插入用户...这是问题吗?
-
感谢您的回复,是的,我需要 users 表中的 company_id 和 user 的新条目,然后再插入 company 的新条目。目前,当我点击提交按钮时,我只有没有 company_id 的用户条目,也没有公司条目。
标签: cakephp