Hou*_*sni 1 relationship lithium
我正在使用Lithium和MySQL.我有一个用户模型,hasOne联系人.联系人模型belongsTo用户.
我在下面列出了我的代码的一个非常基本的版本.
我的问题:
车型/ 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')
);
}
?>
Run Code Online (Sandbox Code Playgroud)
车型/ 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')
);
}
?>
Run Code Online (Sandbox Code Playgroud)
控制器/ 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');
}
}
?>
Run Code Online (Sandbox Code Playgroud)
意见/用户/ 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(); ?>
Run Code Online (Sandbox Code Playgroud)
没有多少人知道这一点,但使用锂可以将表单绑定到多个对象.
在控制器中,返回用户和联系人对象.然后在你的形式:
<?= $this->form->create(compact('user', 'contact')); ?>
Run Code Online (Sandbox Code Playgroud)
然后,您可以将字段呈现为特定对象,如下所示:
<?= $this->form->field('user.name'); ?>
<?= $this->form->field('contact.email'); ?>
Run Code Online (Sandbox Code Playgroud)
当用户提交表单时,两个对象的数据将存储为:
$this->request->data['user'];
$this->request->data['contact'];
Run Code Online (Sandbox Code Playgroud)
您可以像平常一样使用此信息来更新数据库.如果您只想保存来自两个对象的数据有效的信息,可以像这样调用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
}
Run Code Online (Sandbox Code Playgroud)
希望有帮助:)
| 归档时间: |
|
| 查看次数: |
651 次 |
| 最近记录: |