1

我正在将锂与 MySQL 一起使用。我有一个hasOne联系人模型。联系人模型belongsTo用户。

我在下面列出了我的代码的一个非常基本的版本。

我的问题:

  1. 当我编辑用户并提交表单时,如何让 Users::edit 也保存联系人数据?
  2. 另外,如何在用户编辑视图中显示contacts.email?

模型/Users.php

<?php
namespace app\models;

class Users extends \lithium\data\Model {

    public $hasOne = array('Contacts');

    protected $_schema = array(
        'id'   => array('type' => 'integer',
                        'key'  => 'primary'),
        'name' => array('type' => 'varchar')
    );
}
?>

模型/Contacts.php

<?php
namespace app\models;

class Contacts extends \lithium\data\Model {

    public $belongsTo = array('Users');

    protected $_meta = array(
        'key'   => 'user_id',
    );

    protected $_schema = array(
        'user_id' => array('type' => 'integer',
                           'key'  => 'primary'),
        'email'   => array('type' => 'string')
    );
}
?>

控制器/UsersController.php

<?php
namespace app\controllers;

use app\models\Users;

class UsersController extends \lithium\action\Controller {
    public function edit() {
        $user = Users::find('first', array(
                'conditions' => array('id' => $this->request->id),
                'with'       => array('Contacts')
            )
        );

        if (!empty($this->request->data)) {
            if ($user->save($this->request->data)) {
                //flash success message goes here
                return $this->redirect(array('Users::view', 'args' => array($user->id)));
            } else {
                //flash failure message goes here
            }
        }
        return compact('user');
    }
}
?>

意见/用户/edit.html.php

<?php $this->title('Editing User'); ?>
<h2>Editing User</h2>
<?= $this->form->create($user); ?>
    <?= $this->form->field('name'); ?>
    <?= $this->form->field('email', array('type' => 'email')); ?>
<?= $this->form->end(); ?>
4

1 回答 1

5

没有多少人知道这一点,但使用锂,您可以将一个表单绑定到多个对象。

在您的控制器中,返回用户和联系人对象。然后以您的形式:

<?= $this->form->create(compact('user', 'contact')); ?>

然后,您将字段呈现为特定对象,如下所示:

<?= $this->form->field('user.name'); ?>
<?= $this->form->field('contact.email'); ?>

当用户提交表单时,两个对象的数据将存储为:

$this->request->data['user'];
$this->request->data['contact'];

您可以像往常一样使用此信息来更新数据库。如果您只想在来自两个对象的数据都有效的情况下保存信息,您可以像这样调用 validate:

$user = Users::create($this->request->data['user']);
if($user->validates()) {
    $userValid = true;
}

$contact = Contacts::create($this->request->data['contact']);
if($contact->validates()) {
    $contactValid = true;
}

if($userValid && $userValid){
    // save both objects
}

希望有帮助:)

于 2013-05-19T13:10:57.170 回答