【问题标题】:Insert Data in two table using single form in Zend在 Zend 中使用单一表单在两个表中插入数据
【发布时间】:2012-04-19 17:14:46
【问题描述】:

我有两个表“登录”和“个人资料”。 login table 包含 user_id, username, password, typeprofile table 包含 profile_id, user_id, name, address, phone_no,email,status,pancardno,gender,birthday,joiingdate,endingdate。这里我使用user_id 作为reference key。表单包含用户名、密码、类型、姓名、地址、电话号码。那么如何在 Zend Framework 的配置文件表中插入用户名、密码、输入“登录”表和其他字段。
这是我的控制器代码。

include_once(APPLICATION_PATH.'/modules/admin/models/DbTable/Login.php');
public function emppostAction()
{
$session=new Zend_Session_Namespace();
if(isset($session->id))
{
$this->view->name="<b>".$session->name."</b>";
$this->render('employee');

          $data= new Model_DbTable_Login();
          if($this->getRequest()->isPost())
          {
              $un=$this->getRequest()->getPost('un');
              $name=$this->getRequest()->getPost('name');

              $bday=$this->getRequest()->getPost('bday');
              $bmnth=$this->getRequest()->getPost('bmonth');
              $byear=$this->getRequest()->getPost('byear');                   
              $bdate=$byear."-".$bmnth."-".$bday;         

              $jday=$this->getRequest()->getPost('jday');
              $jmnth=$this->getRequest()->getPost('jmonth');
              $jyear=$this->getRequest()->getPost('jyear');
              $jdate=$jyear."-".$jmnth."-".$jday;

              $eday=$this->getRequest()->getPost('eday');
              $emnth=$this->getRequest()->getPost('emonth');
              $eyear=$this->getRequest()->getPost('eyear');                   
              $edate=$eyear."-".$emnth."-".$eday;

              $phoneno=$this->getRequest()->getPost('phoneno');
              $add=$this->getRequest()->getPost('add');   
              $qf=$this->getRequest()->getPost('qf');
              $jod=$this->getRequest()->getPost('jod');
              $email=$this->getRequest()->getPost('email');
              $pwd=$this->getRequest()->getPost('pwd');
              $gn=$this->getRequest()->getPost('gender');
              $ms=$this->getRequest()->getPost('ms');
              $desg=$this->getRequest()->getPost('desig');
              $status=$this->getRequest()->getPost('status');
              $pan=$this->getRequest()->getPost('pancard');


              $insert=$data-> >insertData($un,$pwd$name,$bdate,$phoneno,$add,$qf,$jdate,$edate,$gn,$ms,$desg,$email,$pan,>$status);

          $this->_helper->redirector('viewemp', 'Leave');
              exit;   

          }               
      }
      else
      {
          $this->_helper->redirector('login','index');
      }       

}

在模型中我有

Model_DbTable_Login 类扩展 Zend_Db_Table_Abstract
{
公共函数 insertData($un,$pwd)

{
$data = 数组(
'用户名'=> $un,
'密码'=> $pwd
);
$data2 = 数组( '名称'=> $名称, '生日'=> $bdate, '电话号码'=> $电话号码, '地址'=> $add, '资格'=> $qf, '加入日期'=> $jdate, '结束日期'=> $edate, '性别'=> $gn, 'maritalstatus'=> $ms, '指定'=> $desg, '电子邮件'=> $电子邮件, 'pancardno'=>$pan, '状态'=> $状态 );

  try{  
                  //here i m inserting data in login table.
      $result=$this->insert($data);
                   // now here i want to insert data in profile table
                   $profile=$this->insert($data2)
  }  

捕捉(例外 $e){
echo "
".$e;exit;
}
}

那么在登录表中插入数据的同时,如何在profile表中插入数据呢?

【问题讨论】:

  • loginprofile的关系是1:1吗?如果是这样,在这种情况下合并它们不是更合乎逻辑吗?
  • 是否有理由拥有 profile_id 和 user_id。两个表都索引到 user_id 不是更容易吗?登录表将 user_id 作为自增,而配置文件表将 user_id 作为自然(分配而不是自增)键。除非您允许用户拥有多个个人资料。
  • @Rocky Yathanx Rocky Ford。不需要profile_id。但我无法回答我的问题。你能帮我解决这个问题吗?如何在登录表和配置文件表中插入数据。我可以在登录表中插入数据,但不能在配置文件表中。

标签: zend-framework


【解决方案1】:

好吧,Jigar 让我把这件事简化到我的水平(我想你可能和我很亲近)。

您需要为您打算在应用中使用的每个表创建一个 DbTable 模型。

dbTable 模型的最低要求(所有类使用 ZF 1.11 默认名称和路径):

class Application_Model_DbTable_Login extends Zend_Db_Table_Abstract
{
    //$_name = name of table, not reuired if classname = tablename, but good idea
    protected $_name = 'login';
    //$_primary = primary key column of table, good idea for easy reference.
    protected $_primary = 'user_id';

    //save function added for brevity
    //I like to use the save() method over insert() because for a single row 
    //I can save and update with the same method...easily.
 public function saveUser(array $data) {
    //convert array to standard object for convience
    $dataObject = (object) $data;
    //check if user_id array key exists and isset in original data, if exist will update
    if (array_key_exists('user_id', $data) && isset($data['user_id'])) {
        $row = $this->find($dataObject->id)->current();
    } else {
        //if user_id not set or present in array we create a new row
        $row = $this->createRow();
    }

    $row->username = $dataObject->username;
    $row->password = $dataObject->password;
    $row->type     = $dataObject->type;
    //save or update row
    $row->save();
    //return the whole row object, we'll use it to save data to 'profile'
    return $row;
  }
}

//I would change the profile table to use the user_id as a 'natural' key, this requires adding
//a third property $_sequence = false.
class Application_Model_DbTable_Profile extends Zend_Db_Table_Abstract
{
    //$_name = name of table, not reuired if classname = tablename, but good idea
    protected $_name = 'profile';
    //$_primary = primary key column of table, good idea for easy reference.
    protected $_primary = 'user_id';
    //primary key auto-increment? True for yes false for natural key
    protected $_sequence = FAlSE;

    public function saveUserProfile(array $data, $id) {
    //convert array to standard object for convience
    $dataObject = (object) $data;
    //the user_id will always exist when we deal with the profile
    $row = $this->find($id)->current();
    if (!row)) {
        $row = $this->createRow();
        $row->user_id  = $id;
    } 

    $row->name      = $dataObject->name;
    $row->address   = $dataObject->email;
    $row->phone     = $dataObject->phone;//continue adding fields
    //save or update row
    $row->save();
    //return the whole row object, we'll use it to save data to 'profile'
    return $row;
  }
 }
}

现在通过一个简单的控制器操作来获取我们想要保存的数据。例如,我们将使用默认的 IndexController/indexAction。

class IndexController extends Zend_Controller_Action {


    public function indexAction() {
        $form = new Form(); //add your form here
        //this assumes the use of a Zend_Form object. For other form types use $this->getRquest()->getParams();
        if ($this->getRequest()->isPost() {
            if ($form->isValid($this->getRequest()->getPost()){
            $formData = $form->getValues(); //returns array of filtered/validated form values
           $model = new Application_Model_DbTable_Login();
           //pass the whole array to the saveUser() correct the data in the model.
           $user = $model->saveUser($formData);
           //$user returns the row object we just saved
           $profile = new Application_Model_DbTable_Profile();
           $profile->saveUserProfile($formData, $user->user_id);
      }
    }
    //assign form to view
    $this->view->form = $form;
  }
}

这是一个简单的示例,绝不符合最佳实践,但该技术有效。如果您使用多种表单,indexAction() 中的代码模式将会变得非常熟悉。

我可能会将控制器中的两个 DbTable 调用组合成第三个模型,例如:Application_Model_User

这里要记住的是:在视图/控制器中过滤和验证用户数据,然后在模型中规范化您的数据。您可以将相同的数据数组传递到任何您想要的地方,然后在这里和那里提取一点。

Rob 的回答比我的要正确得多,但它确实包含我们一些业余/初学者程序员还不太了解的概念。 :)

祝你好运。

【讨论】:

  • 谢谢你 vry mch..我在你的帮助下解决了我的问题。非常感谢您...您的帮助在我的项目中帮助了我很多。你说得对,我很成熟。非常感谢您。我还要感谢 Rob 的。谢谢@Rob先生。
【解决方案2】:

创建一个User 实体,该实体包含两个表所需的所有属性。同时创建一个service 对象,用于加载和保存用户实体。

服务器对象,比如UserService,每个表应该有两个属性。您可以使用您编写的两个映射器对象来执行此操作,也可以使用两个Zend_Db_Table 对象。

UserService 上编写一个名为SaveUser($user) 的方法,然后为每个表提取正确的属性并调用相关的表对象进行插入或更新。

同样,创建一个UserService::LoadUser($id),它允许您实例化一个用户实体并从两个表网关对象中填充其属性。

这里有一些示例代码,显示了我的意思。显然它还没有准备好生产!

<?php

class User {
    public $user_id;
    public $username;
    public $password;
    public $profile_id;
    public $name;
    public $address;
    public $phone_no;

}

class LoginTable extends Zend_Db_Table_Abstract
{
    protected $_name = 'login';
}

class ProfileTable extends Zend_Db_Table_Abstract
{
    protected $_name = 'profile';
}

public UserService
{
    public function saveUser(User $user)
    {
        $loginTable = new LoginTable();
        $profileTable = new ProfileTable();

        $loginData = array(
            'username' => $user->username,
            'password' => $user->password,
        );
        $profileData = array(
            'user_id' => $user->user_id,
            'name' => $user->name,
            'address' => $user->address,
            'phone_no' => $user->phone_no,
        );

        if (!user->user_id > 0) {
            // updating
            $loginTable->update($loginData, 'user_id = '. (int)$user->user_id);
            $profileTable->update($profileData, 'profile_id = '. (int)$user->profile_id);
        } else {
            // inserting
            $user->user-id = $loginTable->insert($loginData);
            $profileData['user_id'] = $user->user_id;
            $profileTable->insert($profileData);
        }
    }
}

【讨论】:

  • 感谢 rply @Rob..但我是 zend 新手,所以不知道如何创建用户实体,也不知道映射器对象。
  • 在问题中添加了一些示例代码以显示概念。
  • @RobAllen 我喜欢这个例子。现在是愚蠢的问题。关于实体类的工作原理,我从来没有理解过一件事,使用什么魔法将数据分配给属性?这只是将属性名称与数组键匹配的情况吗?
  • 通常,您需要允许您从表的字段名称映射到实体的属性名称的方法。通常这些存在于映射器类中。在这个示例中,我一直懒惰地直接为 LoginTable 扩展 Zend_Db_Table,但在更复杂的应用程序中,我可能将其称为 LoginMapper 并将表对象作为属性。然后我会在映射器中编写方法以将实体属性转换为表字段名称。
  • @RobAllen 我用了你的例子。但我无法得到解决方案。所以我通过添加控制器的代码和模型的代码来编辑我的问题。先生,您能帮帮我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
相关资源
最近更新 更多