将数据保存在CakePHP中的两个表中

时间:2014-09-03 07:50:49

标签: cakephp

我在Cake中有一个简单的表单:

enter image description here

我想在用户和公司表格中保存信息。

用户表:

enter image description here

公司表:

enter image description here

我需要获得两个SQL查询。

首先: - 使用将在公司表中创建的新公司ID插入新用户。

例如,这个案例,testza,

用户:(新条目) testza密码公司ID(如果新公司条目是新的)

公司(新条目): Id(3)Creaz(姓名)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
        )
    );

}

2 个答案:

答案 0 :(得分:2)

由于您要从下拉菜单中使用数据库中已有的现有公司,请尝试使用Model::saveAssociated()同时保存这两个模型。这将为您立即保存两个记录,并在成功保存时自动将公司id插入到用户表的外键中:User.company_id

通过拨打save()

来替换您的两个saveAssociated()函数调用
if($this->User->saveAssociated($data)) {
    //do something after save.
}

以下是使用现有代码的完整示例:

$this->set('companies', $this->Company->find('list'));

if($this->request->is(array('post', 'put'))) {

    //Dont need to seperate this anymore
    //$d = $this->request->data['User'];
    //$c = $this->request->data['Company'];

    if($this->request->data['User']['password'] != $this->request->data['User']['passwordconfirm']){
        $this->Session->setFlash("Les mots de passes ne correspondent pas","notif",array('type'=>'error'));
    } else {

        if(empty($this->request->data['User']['password']))
            unset($this->request->data['User']['password']);

        if($this->User->saveAssociated($this->request->data)){
            $this->Session->setFlash("L'utilisateur a bien été enregistré","notif");
        }
    }
}

Company模型也缺少用户的hasMany关系。将其添加到Company模型:

public $hasMany = array('User');

有关SaveAssociated()的文档,请参阅“蛋糕手册”: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array

答案 1 :(得分:1)

这里是我建议和我合作的解决方案,首先保存公司首先生成id保存用户:

if($this->Company->save($this->request->data['Company'])){
$this->Company->User->save($this->request->data['User']); // if save doesn't work try $this->Company->User->saveAll($this->request->data['User']);
...
}

更新 在公司模型中添加hasmany关系:

public $hasMany = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'company_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );
希望能有所帮助。