【问题标题】:Save data in two tables in CakePHP在 CakePHP 中将数据保存在两个表中
【发布时间】: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


【解决方案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' => ''
        )
    );

希望有所帮助。

【讨论】:

  • 好的,谢谢,但没有解决。使用 $this->Company->User->save($this->request->data['User']);或 saveAll 现在我没有收到对成员的调用错误,但我仍然只有用户的查询,所以不影响公司表和用户我没有公司的 id,因为公司的条目没有不存在。
  • 看这里:lukrix.com/hasb/companies/signup 你可以看到查询。
  • 还是一样:/我对 UsersController 做了同样的事情
  • 首先,您检索公司表的数据以填充列表,因此您无需重新保存公司,您将只保存用户并且您将拥有 company_id只需编辑视图即可在用户中:Company.company_id 到 User.company_id 并将视图移动到用户而不是公司控制器中。
  • 我明白,但我需要在这个表单中创建一个与用户链接的公司(也是在提交按钮之后创建的),所以我不知道我该怎么做做吧=D
【解决方案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');

请参阅此处的 Cake 手册以获取有关 SaveAssociated() 的文档: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array

【讨论】:

  • 嘿,谢谢你的回答,但我必须把 if($this->User->saveAssociated($data)) { ?
  • 我尝试了您的第二个代码,我添加了与用户有很多关系并且我收到两个错误:警告:/home/lukrixco/public_html/hasb/lib/Cake/ 中的非法字符串偏移 'line'第 653 行的 Utility/Debugger.php 警告 (2):strtolower() 期望参数 1 为字符串,数组给定 [CORE/Cake/Network/CakeRequest.php,第 436 行]
  • @user3790914 我更新了该示例的使用位置。往上看。它应该替换 save() 函数所在的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
相关资源
最近更新 更多