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')
    );
}
?>

models/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'];

この情報を使用して、通常どおりデータベースを更新できます。両方のオブジェクトのデータが有効な場合にのみ情報を保存したい場合は、次のように検証を呼び出すことができます。

$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 に答える